three.webgpu.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {Boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {Boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<String>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {Number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {Boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the typed array for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {TypedArray} The typed array.
  469. */
  470. function getTypedArrayFromType( type ) {
  471. // Handle component type for vectors and matrices
  472. if ( /[iu]?vec\d/.test( type ) ) {
  473. // Handle int vectors
  474. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  475. // Handle uint vectors
  476. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  477. // Default to float vectors
  478. return Float32Array;
  479. }
  480. // Handle matrices (always float)
  481. if ( /mat\d/.test( type ) ) return Float32Array;
  482. // Basic types
  483. if ( /float/.test( type ) ) return Float32Array;
  484. if ( /uint/.test( type ) ) return Uint32Array;
  485. if ( /int/.test( type ) ) return Int32Array;
  486. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  487. }
  488. /**
  489. * Returns the length for the given data type.
  490. *
  491. * @method
  492. * @param {String} type - The data type.
  493. * @return {Number} The length.
  494. */
  495. function getLengthFromType( type ) {
  496. if ( /float|int|uint/.test( type ) ) return 1;
  497. if ( /vec2/.test( type ) ) return 2;
  498. if ( /vec3/.test( type ) ) return 3;
  499. if ( /vec4/.test( type ) ) return 4;
  500. if ( /mat3/.test( type ) ) return 9;
  501. if ( /mat4/.test( type ) ) return 16;
  502. console.error( 'THREE.TSL: Unsupported type:', type );
  503. }
  504. /**
  505. * Returns the data type for the given value.
  506. *
  507. * @method
  508. * @param {Any} value - The value.
  509. * @return {String?} The data type.
  510. */
  511. function getValueType( value ) {
  512. if ( value === undefined || value === null ) return null;
  513. const typeOf = typeof value;
  514. if ( value.isNode === true ) {
  515. return 'node';
  516. } else if ( typeOf === 'number' ) {
  517. return 'float';
  518. } else if ( typeOf === 'boolean' ) {
  519. return 'bool';
  520. } else if ( typeOf === 'string' ) {
  521. return 'string';
  522. } else if ( typeOf === 'function' ) {
  523. return 'shader';
  524. } else if ( value.isVector2 === true ) {
  525. return 'vec2';
  526. } else if ( value.isVector3 === true ) {
  527. return 'vec3';
  528. } else if ( value.isVector4 === true ) {
  529. return 'vec4';
  530. } else if ( value.isMatrix3 === true ) {
  531. return 'mat3';
  532. } else if ( value.isMatrix4 === true ) {
  533. return 'mat4';
  534. } else if ( value.isColor === true ) {
  535. return 'color';
  536. } else if ( value instanceof ArrayBuffer ) {
  537. return 'ArrayBuffer';
  538. }
  539. return null;
  540. }
  541. /**
  542. * Returns the value/object for the given data type and parameters.
  543. *
  544. * @method
  545. * @param {String} type - The given type.
  546. * @param {...Any} params - A parameter list.
  547. * @return {Any} The value/object.
  548. */
  549. function getValueFromType( type, ...params ) {
  550. const last4 = type ? type.slice( -4 ) : undefined;
  551. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  552. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  553. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  554. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  555. }
  556. if ( type === 'color' ) {
  557. return new Color( ...params );
  558. } else if ( last4 === 'vec2' ) {
  559. return new Vector2( ...params );
  560. } else if ( last4 === 'vec3' ) {
  561. return new Vector3( ...params );
  562. } else if ( last4 === 'vec4' ) {
  563. return new Vector4( ...params );
  564. } else if ( last4 === 'mat3' ) {
  565. return new Matrix3( ...params );
  566. } else if ( last4 === 'mat4' ) {
  567. return new Matrix4( ...params );
  568. } else if ( type === 'bool' ) {
  569. return params[ 0 ] || false;
  570. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  571. return params[ 0 ] || 0;
  572. } else if ( type === 'string' ) {
  573. return params[ 0 ] || '';
  574. } else if ( type === 'ArrayBuffer' ) {
  575. return base64ToArrayBuffer( params[ 0 ] );
  576. }
  577. return null;
  578. }
  579. /**
  580. * Gets the object data that can be shared between different rendering steps.
  581. *
  582. * @param {Object} object - The object to get the data for.
  583. * @return {Object} The object data.
  584. */
  585. function getDataFromObject( object ) {
  586. let data = dataFromObject.get( object );
  587. if ( data === undefined ) {
  588. data = {};
  589. dataFromObject.set( object, data );
  590. }
  591. return data;
  592. }
  593. /**
  594. * Converts the given array buffer to a Base64 string.
  595. *
  596. * @method
  597. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  598. * @return {String} The Base64 string.
  599. */
  600. function arrayBufferToBase64( arrayBuffer ) {
  601. let chars = '';
  602. const array = new Uint8Array( arrayBuffer );
  603. for ( let i = 0; i < array.length; i ++ ) {
  604. chars += String.fromCharCode( array[ i ] );
  605. }
  606. return btoa( chars );
  607. }
  608. /**
  609. * Converts the given Base64 string to an array buffer.
  610. *
  611. * @method
  612. * @param {String} base64 - The Base64 string.
  613. * @return {ArrayBuffer} The array buffer.
  614. */
  615. function base64ToArrayBuffer( base64 ) {
  616. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  617. }
  618. var NodeUtils = /*#__PURE__*/Object.freeze({
  619. __proto__: null,
  620. arrayBufferToBase64: arrayBufferToBase64,
  621. base64ToArrayBuffer: base64ToArrayBuffer,
  622. getCacheKey: getCacheKey$1,
  623. getDataFromObject: getDataFromObject,
  624. getLengthFromType: getLengthFromType,
  625. getNodeChildren: getNodeChildren,
  626. getTypeFromLength: getTypeFromLength,
  627. getTypedArrayFromType: getTypedArrayFromType,
  628. getValueFromType: getValueFromType,
  629. getValueType: getValueType,
  630. hash: hash$1,
  631. hashArray: hashArray,
  632. hashString: hashString
  633. });
  634. /** @module NodeConstants **/
  635. /**
  636. * Possible shader stages.
  637. *
  638. * @property {string} VERTEX The vertex shader stage.
  639. * @property {string} FRAGMENT The fragment shader stage.
  640. */
  641. const NodeShaderStage = {
  642. VERTEX: 'vertex',
  643. FRAGMENT: 'fragment'
  644. };
  645. /**
  646. * Update types of a node.
  647. *
  648. * @property {string} NONE The update method is not executed.
  649. * @property {string} FRAME The update method is executed per frame.
  650. * @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.
  651. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  652. */
  653. const NodeUpdateType = {
  654. NONE: 'none',
  655. FRAME: 'frame',
  656. RENDER: 'render',
  657. OBJECT: 'object'
  658. };
  659. /**
  660. * Data types of a node.
  661. *
  662. * @property {string} BOOLEAN Boolean type.
  663. * @property {string} INTEGER Integer type.
  664. * @property {string} FLOAT Float type.
  665. * @property {string} VECTOR2 Two-dimensional vector type.
  666. * @property {string} VECTOR3 Three-dimensional vector type.
  667. * @property {string} VECTOR4 Four-dimensional vector type.
  668. * @property {string} MATRIX2 2x2 matrix type.
  669. * @property {string} MATRIX3 3x3 matrix type.
  670. * @property {string} MATRIX4 4x4 matrix type.
  671. */
  672. const NodeType = {
  673. BOOLEAN: 'bool',
  674. INTEGER: 'int',
  675. FLOAT: 'float',
  676. VECTOR2: 'vec2',
  677. VECTOR3: 'vec3',
  678. VECTOR4: 'vec4',
  679. MATRIX2: 'mat2',
  680. MATRIX3: 'mat3',
  681. MATRIX4: 'mat4'
  682. };
  683. /**
  684. * Access types of a node. These are relevant for compute and storage usage.
  685. *
  686. * @property {string} READ_ONLY Read-only access
  687. * @property {string} WRITE_ONLY Write-only access.
  688. * @property {string} READ_WRITE Read and write access.
  689. */
  690. const NodeAccess = {
  691. READ_ONLY: 'readOnly',
  692. WRITE_ONLY: 'writeOnly',
  693. READ_WRITE: 'readWrite',
  694. };
  695. const defaultShaderStages = [ 'fragment', 'vertex' ];
  696. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  697. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  698. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  699. let _nodeId = 0;
  700. /**
  701. * Base class for all nodes.
  702. *
  703. * @augments EventDispatcher
  704. */
  705. class Node extends EventDispatcher {
  706. static get type() {
  707. return 'Node';
  708. }
  709. /**
  710. * Constructs a new node.
  711. *
  712. * @param {String?} nodeType - The node type.
  713. */
  714. constructor( nodeType = null ) {
  715. super();
  716. /**
  717. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  718. *
  719. * @type {String?}
  720. * @default null
  721. */
  722. this.nodeType = nodeType;
  723. /**
  724. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  725. *
  726. * @type {String}
  727. * @default 'none'
  728. */
  729. this.updateType = NodeUpdateType.NONE;
  730. /**
  731. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  732. *
  733. * @type {String}
  734. * @default 'none'
  735. */
  736. this.updateBeforeType = NodeUpdateType.NONE;
  737. /**
  738. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  739. *
  740. * @type {String}
  741. * @default 'none'
  742. */
  743. this.updateAfterType = NodeUpdateType.NONE;
  744. /**
  745. * The UUID of the node.
  746. *
  747. * @type {String}
  748. * @readonly
  749. */
  750. this.uuid = MathUtils.generateUUID();
  751. /**
  752. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  753. *
  754. * @type {Number}
  755. * @readonly
  756. * @default 0
  757. */
  758. this.version = 0;
  759. /**
  760. * Whether this node is global or not. This property is relevant for the internal
  761. * node caching system. All nodes which should be declared just once should
  762. * set this flag to `true` (a typical example is {@link AttributeNode}).
  763. *
  764. * @type {Boolean}
  765. * @default false
  766. */
  767. this.global = false;
  768. /**
  769. * This flag can be used for type testing.
  770. *
  771. * @type {Boolean}
  772. * @readonly
  773. * @default true
  774. */
  775. this.isNode = true;
  776. // private
  777. /**
  778. * The cache key of this node.
  779. *
  780. * @private
  781. * @type {Number?}
  782. * @default null
  783. */
  784. this._cacheKey = null;
  785. /**
  786. * The cache key 's version.
  787. *
  788. * @private
  789. * @type {Number}
  790. * @default 0
  791. */
  792. this._cacheKeyVersion = 0;
  793. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  794. }
  795. /**
  796. * Set this property to `true` when the node should be regenerated.
  797. *
  798. * @type {Boolean}
  799. * @default false
  800. * @param {boolean} value
  801. */
  802. set needsUpdate( value ) {
  803. if ( value === true ) {
  804. this.version ++;
  805. }
  806. }
  807. /**
  808. * The type of the class. The value is usually the constructor name.
  809. *
  810. * @type {String}
  811. * @readonly
  812. */
  813. get type() {
  814. return this.constructor.type;
  815. }
  816. /**
  817. * Convenient method for defining {@link Node#update}.
  818. *
  819. * @param {Function} callback - The update method.
  820. * @param {String} updateType - The update type.
  821. * @return {Node} A reference to this node.
  822. */
  823. onUpdate( callback, updateType ) {
  824. this.updateType = updateType;
  825. this.update = callback.bind( this.getSelf() );
  826. return this;
  827. }
  828. /**
  829. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  830. * this method automatically sets the update type to `FRAME`.
  831. *
  832. * @param {Function} callback - The update method.
  833. * @return {Node} A reference to this node.
  834. */
  835. onFrameUpdate( callback ) {
  836. return this.onUpdate( callback, NodeUpdateType.FRAME );
  837. }
  838. /**
  839. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  840. * this method automatically sets the update type to `RENDER`.
  841. *
  842. * @param {Function} callback - The update method.
  843. * @return {Node} A reference to this node.
  844. */
  845. onRenderUpdate( callback ) {
  846. return this.onUpdate( callback, NodeUpdateType.RENDER );
  847. }
  848. /**
  849. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  850. * this method automatically sets the update type to `OBJECT`.
  851. *
  852. * @param {Function} callback - The update method.
  853. * @return {Node} A reference to this node.
  854. */
  855. onObjectUpdate( callback ) {
  856. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  857. }
  858. /**
  859. * Convenient method for defining {@link Node#updateReference}.
  860. *
  861. * @param {Function} callback - The update method.
  862. * @return {Node} A reference to this node.
  863. */
  864. onReference( callback ) {
  865. this.updateReference = callback.bind( this.getSelf() );
  866. return this;
  867. }
  868. /**
  869. * The `this` reference might point to a Proxy so this method can be used
  870. * to get the reference to the actual node instance.
  871. *
  872. * @return {Node} A reference to the node.
  873. */
  874. getSelf() {
  875. // Returns non-node object.
  876. return this.self || this;
  877. }
  878. /**
  879. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  880. * to such objects based on a given state (e.g. the current node frame or builder).
  881. *
  882. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  883. * @return {Any} The updated reference.
  884. */
  885. updateReference( /*state*/ ) {
  886. return this;
  887. }
  888. /**
  889. * By default this method returns the value of the {@link Node#global} flag. This method
  890. * can be overwritten in derived classes if an analytical way is required to determine the
  891. * global status.
  892. *
  893. * @param {NodeBuilder} builder - The current node builder.
  894. * @return {Boolean} Whether this node is global or not.
  895. */
  896. isGlobal( /*builder*/ ) {
  897. return this.global;
  898. }
  899. /**
  900. * Generator function that can be used to iterate over the child nodes.
  901. *
  902. * @generator
  903. * @yields {Node} A child node.
  904. */
  905. * getChildren() {
  906. for ( const { childNode } of getNodeChildren( this ) ) {
  907. yield childNode;
  908. }
  909. }
  910. /**
  911. * Calling this method dispatches the `dispose` event. This event can be used
  912. * to register event listeners for clean up tasks.
  913. */
  914. dispose() {
  915. this.dispatchEvent( { type: 'dispose' } );
  916. }
  917. /**
  918. * Callback for {@link Node#traverse}.
  919. *
  920. * @callback traverseCallback
  921. * @param {Node} node - The current node.
  922. */
  923. /**
  924. * Can be used to traverse through the node's hierarchy.
  925. *
  926. * @param {traverseCallback} callback - A callback that is executed per node.
  927. */
  928. traverse( callback ) {
  929. callback( this );
  930. for ( const childNode of this.getChildren() ) {
  931. childNode.traverse( callback );
  932. }
  933. }
  934. /**
  935. * Returns the cache key for this node.
  936. *
  937. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  938. * @return {Number} The cache key of the node.
  939. */
  940. getCacheKey( force = false ) {
  941. force = force || this.version !== this._cacheKeyVersion;
  942. if ( force === true || this._cacheKey === null ) {
  943. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  944. this._cacheKeyVersion = this.version;
  945. }
  946. return this._cacheKey;
  947. }
  948. /**
  949. * Generate a custom cache key for this node.
  950. *
  951. * @return {Number} The cache key of the node.
  952. */
  953. customCacheKey() {
  954. return 0;
  955. }
  956. /**
  957. * Returns the references to this node which is by default `this`.
  958. *
  959. * @return {Node} A reference to this node.
  960. */
  961. getScope() {
  962. return this;
  963. }
  964. /**
  965. * Returns the hash of the node which is used to identify the node. By default it's
  966. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  967. * depending on their implementation.
  968. *
  969. * @param {NodeBuilder} builder - The current node builder.
  970. * @return {String} The hash.
  971. */
  972. getHash( /*builder*/ ) {
  973. return this.uuid;
  974. }
  975. /**
  976. * Returns the update type of {@link Node#update}.
  977. *
  978. * @return {NodeUpdateType} The update type.
  979. */
  980. getUpdateType() {
  981. return this.updateType;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#updateBefore}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateBeforeType() {
  989. return this.updateBeforeType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateAfter}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateAfterType() {
  997. return this.updateAfterType;
  998. }
  999. /**
  1000. * Certain types are composed of multiple elements. For example a `vec3`
  1001. * is composed of three `float` values. This method returns the type of
  1002. * these elements.
  1003. *
  1004. * @param {NodeBuilder} builder - The current node builder.
  1005. * @return {String} The type of the node.
  1006. */
  1007. getElementType( builder ) {
  1008. const type = this.getNodeType( builder );
  1009. const elementType = builder.getElementType( type );
  1010. return elementType;
  1011. }
  1012. /**
  1013. * Returns the node's type.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {String} The type of the node.
  1017. */
  1018. getNodeType( builder ) {
  1019. const nodeProperties = builder.getNodeProperties( this );
  1020. if ( nodeProperties.outputNode ) {
  1021. return nodeProperties.outputNode.getNodeType( builder );
  1022. }
  1023. return this.nodeType;
  1024. }
  1025. /**
  1026. * This method is used during the build process of a node and ensures
  1027. * equal nodes are not built multiple times but just once. For example if
  1028. * `attribute( 'uv' )` is used multiple times by the user, the build
  1029. * process makes sure to process just the first node.
  1030. *
  1031. * @param {NodeBuilder} builder - The current node builder.
  1032. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1033. */
  1034. getShared( builder ) {
  1035. const hash = this.getHash( builder );
  1036. const nodeFromHash = builder.getNodeFromHash( hash );
  1037. return nodeFromHash || this;
  1038. }
  1039. /**
  1040. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1041. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1042. * The output node must be returned in the `return` statement.
  1043. *
  1044. * @param {NodeBuilder} builder - The current node builder.
  1045. * @return {Node?} The output node.
  1046. */
  1047. setup( builder ) {
  1048. const nodeProperties = builder.getNodeProperties( this );
  1049. let index = 0;
  1050. for ( const childNode of this.getChildren() ) {
  1051. nodeProperties[ 'node' + index ++ ] = childNode;
  1052. }
  1053. // return a outputNode if exists or null
  1054. return nodeProperties.outputNode || null;
  1055. }
  1056. /**
  1057. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1058. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1059. *
  1060. * @param {NodeBuilder} builder - The current node builder.
  1061. */
  1062. analyze( builder ) {
  1063. const usageCount = builder.increaseUsage( this );
  1064. if ( usageCount === 1 ) {
  1065. // node flow children
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. for ( const childNode of Object.values( nodeProperties ) ) {
  1068. if ( childNode && childNode.isNode === true ) {
  1069. childNode.build( builder );
  1070. }
  1071. }
  1072. }
  1073. }
  1074. /**
  1075. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1076. * This state builds the output node and returns the resulting shader string.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. * @param {String?} output - Can be used to define the output type.
  1080. * @return {String?} The generated shader string.
  1081. */
  1082. generate( builder, output ) {
  1083. const { outputNode } = builder.getNodeProperties( this );
  1084. if ( outputNode && outputNode.isNode === true ) {
  1085. return outputNode.build( builder, output );
  1086. }
  1087. }
  1088. /**
  1089. * The method can be implemented to update the node's internal state before it is used to render an object.
  1090. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1091. *
  1092. * @abstract
  1093. * @param {NodeFrame} frame - A reference to the current node frame.
  1094. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1095. */
  1096. updateBefore( /*frame*/ ) {
  1097. console.warn( 'Abstract function.' );
  1098. }
  1099. /**
  1100. * The method can be implemented to update the node's internal state after it was used to render an object.
  1101. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1102. *
  1103. * @abstract
  1104. * @param {NodeFrame} frame - A reference to the current node frame.
  1105. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1106. */
  1107. updateAfter( /*frame*/ ) {
  1108. console.warn( 'Abstract function.' );
  1109. }
  1110. /**
  1111. * The method can be implemented to update the node's internal state when it is used to render an object.
  1112. * The {@link Node#updateType} property defines how often the update is executed.
  1113. *
  1114. * @abstract
  1115. * @param {NodeFrame} frame - A reference to the current node frame.
  1116. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1117. */
  1118. update( /*frame*/ ) {
  1119. console.warn( 'Abstract function.' );
  1120. }
  1121. /**
  1122. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1123. * on the current build stage (setup, analyze or generate).
  1124. *
  1125. * @param {NodeBuilder} builder - The current node builder.
  1126. * @param {String?} output - Can be used to define the output type.
  1127. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1128. */
  1129. build( builder, output = null ) {
  1130. const refNode = this.getShared( builder );
  1131. if ( this !== refNode ) {
  1132. return refNode.build( builder, output );
  1133. }
  1134. builder.addNode( this );
  1135. builder.addChain( this );
  1136. /* Build stages expected results:
  1137. - "setup" -> Node
  1138. - "analyze" -> null
  1139. - "generate" -> String
  1140. */
  1141. let result = null;
  1142. const buildStage = builder.getBuildStage();
  1143. if ( buildStage === 'setup' ) {
  1144. this.updateReference( builder );
  1145. const properties = builder.getNodeProperties( this );
  1146. if ( properties.initialized !== true ) {
  1147. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1148. properties.initialized = true;
  1149. const outputNode = this.setup( builder ); // return a node or null
  1150. const isNodeOutput = outputNode && outputNode.isNode === true;
  1151. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1152. // !! no outputNode !!
  1153. //outputNode = builder.stack;
  1154. }*/
  1155. for ( const childNode of Object.values( properties ) ) {
  1156. if ( childNode && childNode.isNode === true ) {
  1157. childNode.build( builder );
  1158. }
  1159. }
  1160. if ( isNodeOutput ) {
  1161. outputNode.build( builder );
  1162. }
  1163. properties.outputNode = outputNode;
  1164. }
  1165. } else if ( buildStage === 'analyze' ) {
  1166. this.analyze( builder );
  1167. } else if ( buildStage === 'generate' ) {
  1168. const isGenerateOnce = this.generate.length === 1;
  1169. if ( isGenerateOnce ) {
  1170. const type = this.getNodeType( builder );
  1171. const nodeData = builder.getDataFromNode( this );
  1172. result = nodeData.snippet;
  1173. if ( result === undefined ) {
  1174. result = this.generate( builder ) || '';
  1175. nodeData.snippet = result;
  1176. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1177. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1178. }
  1179. result = builder.format( result, type, output );
  1180. } else {
  1181. result = this.generate( builder, output ) || '';
  1182. }
  1183. }
  1184. builder.removeChain( this );
  1185. builder.addSequentialNode( this );
  1186. return result;
  1187. }
  1188. /**
  1189. * Returns the child nodes as a JSON object.
  1190. *
  1191. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1192. */
  1193. getSerializeChildren() {
  1194. return getNodeChildren( this );
  1195. }
  1196. /**
  1197. * Serializes the node to JSON.
  1198. *
  1199. * @param {Object} json - The output JSON object.
  1200. */
  1201. serialize( json ) {
  1202. const nodeChildren = this.getSerializeChildren();
  1203. const inputNodes = {};
  1204. for ( const { property, index, childNode } of nodeChildren ) {
  1205. if ( index !== undefined ) {
  1206. if ( inputNodes[ property ] === undefined ) {
  1207. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1208. }
  1209. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1210. } else {
  1211. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1212. }
  1213. }
  1214. if ( Object.keys( inputNodes ).length > 0 ) {
  1215. json.inputNodes = inputNodes;
  1216. }
  1217. }
  1218. /**
  1219. * Deserializes the node from the given JSON.
  1220. *
  1221. * @param {Object} json - The JSON object.
  1222. */
  1223. deserialize( json ) {
  1224. if ( json.inputNodes !== undefined ) {
  1225. const nodes = json.meta.nodes;
  1226. for ( const property in json.inputNodes ) {
  1227. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1228. const inputArray = [];
  1229. for ( const uuid of json.inputNodes[ property ] ) {
  1230. inputArray.push( nodes[ uuid ] );
  1231. }
  1232. this[ property ] = inputArray;
  1233. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1234. const inputObject = {};
  1235. for ( const subProperty in json.inputNodes[ property ] ) {
  1236. const uuid = json.inputNodes[ property ][ subProperty ];
  1237. inputObject[ subProperty ] = nodes[ uuid ];
  1238. }
  1239. this[ property ] = inputObject;
  1240. } else {
  1241. const uuid = json.inputNodes[ property ];
  1242. this[ property ] = nodes[ uuid ];
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Serializes the node into the three.js JSON Object/Scene format.
  1249. *
  1250. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1251. * @return {Object} The serialized node.
  1252. */
  1253. toJSON( meta ) {
  1254. const { uuid, type } = this;
  1255. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1256. if ( isRoot ) {
  1257. meta = {
  1258. textures: {},
  1259. images: {},
  1260. nodes: {}
  1261. };
  1262. }
  1263. // serialize
  1264. let data = meta.nodes[ uuid ];
  1265. if ( data === undefined ) {
  1266. data = {
  1267. uuid,
  1268. type,
  1269. meta,
  1270. metadata: {
  1271. version: 4.6,
  1272. type: 'Node',
  1273. generator: 'Node.toJSON'
  1274. }
  1275. };
  1276. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1277. this.serialize( data );
  1278. delete data.meta;
  1279. }
  1280. // TODO: Copied from Object3D.toJSON
  1281. function extractFromCache( cache ) {
  1282. const values = [];
  1283. for ( const key in cache ) {
  1284. const data = cache[ key ];
  1285. delete data.metadata;
  1286. values.push( data );
  1287. }
  1288. return values;
  1289. }
  1290. if ( isRoot ) {
  1291. const textures = extractFromCache( meta.textures );
  1292. const images = extractFromCache( meta.images );
  1293. const nodes = extractFromCache( meta.nodes );
  1294. if ( textures.length > 0 ) data.textures = textures;
  1295. if ( images.length > 0 ) data.images = images;
  1296. if ( nodes.length > 0 ) data.nodes = nodes;
  1297. }
  1298. return data;
  1299. }
  1300. }
  1301. /**
  1302. * Base class for representing element access on an array-like
  1303. * node data structures.
  1304. *
  1305. * @augments Node
  1306. */
  1307. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1308. static get type() {
  1309. return 'ArrayElementNode';
  1310. }
  1311. /**
  1312. * Constructs an array element node.
  1313. *
  1314. * @param {Node} node - The array-like node.
  1315. * @param {Node} indexNode - The index node that defines the element access.
  1316. */
  1317. constructor( node, indexNode ) {
  1318. super();
  1319. /**
  1320. * The array-like node.
  1321. *
  1322. * @type {Node}
  1323. */
  1324. this.node = node;
  1325. /**
  1326. * The index node that defines the element access.
  1327. *
  1328. * @type {Node}
  1329. */
  1330. this.indexNode = indexNode;
  1331. /**
  1332. * This flag can be used for type testing.
  1333. *
  1334. * @type {Boolean}
  1335. * @readonly
  1336. * @default true
  1337. */
  1338. this.isArrayElementNode = true;
  1339. }
  1340. /**
  1341. * This method is overwritten since the node type is inferred from the array-like node.
  1342. *
  1343. * @param {NodeBuilder} builder - The current node builder.
  1344. * @return {String} The node type.
  1345. */
  1346. getNodeType( builder ) {
  1347. return this.node.getElementType( builder );
  1348. }
  1349. generate( builder ) {
  1350. const nodeSnippet = this.node.build( builder );
  1351. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1352. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1353. }
  1354. }
  1355. /**
  1356. * This module is part of the TSL core and usually not used in app level code.
  1357. * It represents a convert operation during the shader generation process
  1358. * meaning it converts the data type of a node to a target data type.
  1359. *
  1360. * @augments Node
  1361. */
  1362. class ConvertNode extends Node {
  1363. static get type() {
  1364. return 'ConvertNode';
  1365. }
  1366. /**
  1367. * Constructs a new convert node.
  1368. *
  1369. * @param {Node} node - The node which type should be converted.
  1370. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1371. */
  1372. constructor( node, convertTo ) {
  1373. super();
  1374. /**
  1375. * The node which type should be converted.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.node = node;
  1380. /**
  1381. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1382. *
  1383. * @type {String}
  1384. */
  1385. this.convertTo = convertTo;
  1386. }
  1387. /**
  1388. * This method is overwritten since the implementation tries to infer the best
  1389. * matching type from the {@link ConvertNode#convertTo} property.
  1390. *
  1391. * @param {NodeBuilder} builder - The current node builder.
  1392. * @return {String} The node type.
  1393. */
  1394. getNodeType( builder ) {
  1395. const requestType = this.node.getNodeType( builder );
  1396. let convertTo = null;
  1397. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1398. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1399. convertTo = overloadingType;
  1400. }
  1401. }
  1402. return convertTo;
  1403. }
  1404. serialize( data ) {
  1405. super.serialize( data );
  1406. data.convertTo = this.convertTo;
  1407. }
  1408. deserialize( data ) {
  1409. super.deserialize( data );
  1410. this.convertTo = data.convertTo;
  1411. }
  1412. generate( builder, output ) {
  1413. const node = this.node;
  1414. const type = this.getNodeType( builder );
  1415. const snippet = node.build( builder, type );
  1416. return builder.format( snippet, type, output );
  1417. }
  1418. }
  1419. /**
  1420. * This module uses cache management to create temporary variables
  1421. * if the node is used more than once to prevent duplicate calculations.
  1422. *
  1423. * The class acts as a base class for many other nodes types.
  1424. *
  1425. * @augments Node
  1426. */
  1427. class TempNode extends Node {
  1428. static get type() {
  1429. return 'TempNode';
  1430. }
  1431. /**
  1432. * Constructs a temp node.
  1433. *
  1434. * @param {String?} nodeType - The node type.
  1435. */
  1436. constructor( nodeType = null ) {
  1437. super( nodeType );
  1438. /**
  1439. * This flag can be used for type testing.
  1440. *
  1441. * @type {Boolean}
  1442. * @readonly
  1443. * @default true
  1444. */
  1445. this.isTempNode = true;
  1446. }
  1447. /**
  1448. * Whether this node is used more than once in context of other nodes.
  1449. *
  1450. * @param {NodeBuilder} builder - The node builder.
  1451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1452. */
  1453. hasDependencies( builder ) {
  1454. return builder.getDataFromNode( this ).usageCount > 1;
  1455. }
  1456. build( builder, output ) {
  1457. const buildStage = builder.getBuildStage();
  1458. if ( buildStage === 'generate' ) {
  1459. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1460. const nodeData = builder.getDataFromNode( this );
  1461. if ( nodeData.propertyName !== undefined ) {
  1462. return builder.format( nodeData.propertyName, type, output );
  1463. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1464. const snippet = super.build( builder, type );
  1465. const nodeVar = builder.getVarFromNode( this, null, type );
  1466. const propertyName = builder.getPropertyName( nodeVar );
  1467. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1468. nodeData.snippet = snippet;
  1469. nodeData.propertyName = propertyName;
  1470. return builder.format( nodeData.propertyName, type, output );
  1471. }
  1472. }
  1473. return super.build( builder, output );
  1474. }
  1475. }
  1476. /**
  1477. * This module is part of the TSL core and usually not used in app level code.
  1478. * It represents a join operation during the shader generation process.
  1479. * For example in can compose/join two single floats into a `vec2` type.
  1480. *
  1481. * @augments TempNode
  1482. */
  1483. class JoinNode extends TempNode {
  1484. static get type() {
  1485. return 'JoinNode';
  1486. }
  1487. /**
  1488. * Constructs a new join node.
  1489. *
  1490. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1491. * @param {String?} [nodeType=null] - The node type.
  1492. */
  1493. constructor( nodes = [], nodeType = null ) {
  1494. super( nodeType );
  1495. /**
  1496. * An array of nodes that should be joined.
  1497. *
  1498. * @type {Array<Node>}
  1499. */
  1500. this.nodes = nodes;
  1501. }
  1502. /**
  1503. * This method is overwritten since the node type must be inferred from the
  1504. * joined data length if not explicitly defined.
  1505. *
  1506. * @param {NodeBuilder} builder - The current node builder.
  1507. * @return {String} The node type.
  1508. */
  1509. getNodeType( builder ) {
  1510. if ( this.nodeType !== null ) {
  1511. return builder.getVectorType( this.nodeType );
  1512. }
  1513. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1514. }
  1515. generate( builder, output ) {
  1516. const type = this.getNodeType( builder );
  1517. const nodes = this.nodes;
  1518. const primitiveType = builder.getComponentType( type );
  1519. const snippetValues = [];
  1520. for ( const input of nodes ) {
  1521. let inputSnippet = input.build( builder );
  1522. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1523. if ( inputPrimitiveType !== primitiveType ) {
  1524. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1525. }
  1526. snippetValues.push( inputSnippet );
  1527. }
  1528. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1529. return builder.format( snippet, type, output );
  1530. }
  1531. }
  1532. const _stringVectorComponents = vectorComponents.join( '' );
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * `SplitNode` represents a property access operation which means it is
  1536. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1537. * For example:
  1538. * ```js
  1539. * const redValue = color.r;
  1540. * ```
  1541. *
  1542. * @augments Node
  1543. */
  1544. class SplitNode extends Node {
  1545. static get type() {
  1546. return 'SplitNode';
  1547. }
  1548. /**
  1549. * Constructs a new split node.
  1550. *
  1551. * @param {Node} node - The node that should be accessed.
  1552. * @param {String} [components='x'] - The components that should be accessed.
  1553. */
  1554. constructor( node, components = 'x' ) {
  1555. super();
  1556. /**
  1557. * The node that should be accessed.
  1558. *
  1559. * @type {Node}
  1560. */
  1561. this.node = node;
  1562. /**
  1563. * The components that should be accessed.
  1564. *
  1565. * @type {string}
  1566. */
  1567. this.components = components;
  1568. /**
  1569. * This flag can be used for type testing.
  1570. *
  1571. * @type {Boolean}
  1572. * @readonly
  1573. * @default true
  1574. */
  1575. this.isSplitNode = true;
  1576. }
  1577. /**
  1578. * Returns the vector length which is computed based on the requested components.
  1579. *
  1580. * @return {Number} The vector length.
  1581. */
  1582. getVectorLength() {
  1583. let vectorLength = this.components.length;
  1584. for ( const c of this.components ) {
  1585. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1586. }
  1587. return vectorLength;
  1588. }
  1589. /**
  1590. * Returns the component type of the node's type.
  1591. *
  1592. * @param {NodeBuilder} builder - The current node builder.
  1593. * @return {String} The component type.
  1594. */
  1595. getComponentType( builder ) {
  1596. return builder.getComponentType( this.node.getNodeType( builder ) );
  1597. }
  1598. /**
  1599. * This method is overwritten since the node type is inferred from requested components.
  1600. *
  1601. * @param {NodeBuilder} builder - The current node builder.
  1602. * @return {String} The node type.
  1603. */
  1604. getNodeType( builder ) {
  1605. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1606. }
  1607. generate( builder, output ) {
  1608. const node = this.node;
  1609. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1610. let snippet = null;
  1611. if ( nodeTypeLength > 1 ) {
  1612. let type = null;
  1613. const componentsLength = this.getVectorLength();
  1614. if ( componentsLength >= nodeTypeLength ) {
  1615. // needed expand the input node
  1616. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1617. }
  1618. const nodeSnippet = node.build( builder, type );
  1619. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1620. // unnecessary swizzle
  1621. snippet = builder.format( nodeSnippet, type, output );
  1622. } else {
  1623. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1624. }
  1625. } else {
  1626. // ignore .components if .node returns float/integer
  1627. snippet = node.build( builder, output );
  1628. }
  1629. return snippet;
  1630. }
  1631. serialize( data ) {
  1632. super.serialize( data );
  1633. data.components = this.components;
  1634. }
  1635. deserialize( data ) {
  1636. super.deserialize( data );
  1637. this.components = data.components;
  1638. }
  1639. }
  1640. /**
  1641. * This module is part of the TSL core and usually not used in app level code.
  1642. * `SetNode` represents a set operation which means it is used to implement any
  1643. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1644. * For example:
  1645. * ```js
  1646. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1647. * ```
  1648. *
  1649. * @augments TempNode
  1650. */
  1651. class SetNode extends TempNode {
  1652. static get type() {
  1653. return 'SetNode';
  1654. }
  1655. /**
  1656. * Constructs a new set node.
  1657. *
  1658. * @param {Node} sourceNode - The node that should be updated.
  1659. * @param {String} components - The components that should be updated.
  1660. * @param {Node} targetNode - The value node.
  1661. */
  1662. constructor( sourceNode, components, targetNode ) {
  1663. super();
  1664. /**
  1665. * The node that should be updated.
  1666. *
  1667. * @type {Node}
  1668. */
  1669. this.sourceNode = sourceNode;
  1670. /**
  1671. * The components that should be updated.
  1672. *
  1673. * @type {String}
  1674. */
  1675. this.components = components;
  1676. /**
  1677. * The value node.
  1678. *
  1679. * @type {Node}
  1680. */
  1681. this.targetNode = targetNode;
  1682. }
  1683. /**
  1684. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1685. *
  1686. * @param {NodeBuilder} builder - The current node builder.
  1687. * @return {String} The node type.
  1688. */
  1689. getNodeType( builder ) {
  1690. return this.sourceNode.getNodeType( builder );
  1691. }
  1692. generate( builder ) {
  1693. const { sourceNode, components, targetNode } = this;
  1694. const sourceType = this.getNodeType( builder );
  1695. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1696. const targetType = builder.getTypeFromLength( components.length, componentType );
  1697. const targetSnippet = targetNode.build( builder, targetType );
  1698. const sourceSnippet = sourceNode.build( builder, sourceType );
  1699. const length = builder.getTypeLength( sourceType );
  1700. const snippetValues = [];
  1701. for ( let i = 0; i < length; i ++ ) {
  1702. const component = vectorComponents[ i ];
  1703. if ( component === components[ 0 ] ) {
  1704. snippetValues.push( targetSnippet );
  1705. i += components.length - 1;
  1706. } else {
  1707. snippetValues.push( sourceSnippet + '.' + component );
  1708. }
  1709. }
  1710. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1711. }
  1712. }
  1713. /**
  1714. * This module is part of the TSL core and usually not used in app level code.
  1715. * It represents a flip operation during the shader generation process
  1716. * meaning it flips normalized values with the following formula:
  1717. * ```
  1718. * x = 1 - x;
  1719. * ```
  1720. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1721. * `flipSTPQ()` method invocations on node objects. For example:
  1722. * ```js
  1723. * uvNode = uvNode.flipY();
  1724. * ```
  1725. *
  1726. * @augments TempNode
  1727. */
  1728. class FlipNode extends TempNode {
  1729. static get type() {
  1730. return 'FlipNode';
  1731. }
  1732. /**
  1733. * Constructs a new flip node.
  1734. *
  1735. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1736. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1737. */
  1738. constructor( sourceNode, components ) {
  1739. super();
  1740. /**
  1741. * The node which component(s) should be flipped.
  1742. *
  1743. * @type {Node}
  1744. */
  1745. this.sourceNode = sourceNode;
  1746. /**
  1747. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1748. *
  1749. * @type {String}
  1750. */
  1751. this.components = components;
  1752. }
  1753. /**
  1754. * This method is overwritten since the node type is inferred from the source node.
  1755. *
  1756. * @param {NodeBuilder} builder - The current node builder.
  1757. * @return {String} The node type.
  1758. */
  1759. getNodeType( builder ) {
  1760. return this.sourceNode.getNodeType( builder );
  1761. }
  1762. generate( builder ) {
  1763. const { components, sourceNode } = this;
  1764. const sourceType = this.getNodeType( builder );
  1765. const sourceSnippet = sourceNode.build( builder );
  1766. const sourceCache = builder.getVarFromNode( this );
  1767. const sourceProperty = builder.getPropertyName( sourceCache );
  1768. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1769. const length = builder.getTypeLength( sourceType );
  1770. const snippetValues = [];
  1771. let componentIndex = 0;
  1772. for ( let i = 0; i < length; i ++ ) {
  1773. const component = vectorComponents[ i ];
  1774. if ( component === components[ componentIndex ] ) {
  1775. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1776. componentIndex ++;
  1777. } else {
  1778. snippetValues.push( sourceProperty + '.' + component );
  1779. }
  1780. }
  1781. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1782. }
  1783. }
  1784. /**
  1785. * Base class for representing data input nodes.
  1786. *
  1787. * @augments Node
  1788. */
  1789. class InputNode extends Node {
  1790. static get type() {
  1791. return 'InputNode';
  1792. }
  1793. /**
  1794. * Constructs a new input node.
  1795. *
  1796. * @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).
  1797. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1798. */
  1799. constructor( value, nodeType = null ) {
  1800. super( nodeType );
  1801. /**
  1802. * This flag can be used for type testing.
  1803. *
  1804. * @type {Boolean}
  1805. * @readonly
  1806. * @default true
  1807. */
  1808. this.isInputNode = true;
  1809. /**
  1810. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1811. *
  1812. * @type {Any}
  1813. */
  1814. this.value = value;
  1815. /**
  1816. * The precision of the value in the shader.
  1817. *
  1818. * @type {('low'|'medium'|'high')?}
  1819. * @default null
  1820. */
  1821. this.precision = null;
  1822. }
  1823. getNodeType( /*builder*/ ) {
  1824. if ( this.nodeType === null ) {
  1825. return getValueType( this.value );
  1826. }
  1827. return this.nodeType;
  1828. }
  1829. /**
  1830. * Returns the input type of the node which is by default the node type. Derived modules
  1831. * might overwrite this method and use a fixed type or compute one analytically.
  1832. *
  1833. * A typical example for different input and node types are textures. The input type of a
  1834. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1835. *
  1836. * @param {NodeBuilder} builder - The current node builder.
  1837. * @return {String} The input type.
  1838. */
  1839. getInputType( builder ) {
  1840. return this.getNodeType( builder );
  1841. }
  1842. /**
  1843. * Sets the precision to the given value. The method can be
  1844. * overwritten in derived classes if the final precision must be computed
  1845. * analytically.
  1846. *
  1847. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1848. * @return {InputNode} A reference to this node.
  1849. */
  1850. setPrecision( precision ) {
  1851. this.precision = precision;
  1852. return this;
  1853. }
  1854. serialize( data ) {
  1855. super.serialize( data );
  1856. data.value = this.value;
  1857. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1858. data.valueType = getValueType( this.value );
  1859. data.nodeType = this.nodeType;
  1860. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1861. data.precision = this.precision;
  1862. }
  1863. deserialize( data ) {
  1864. super.deserialize( data );
  1865. this.nodeType = data.nodeType;
  1866. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1867. this.precision = data.precision || null;
  1868. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1869. }
  1870. generate( /*builder, output*/ ) {
  1871. console.warn( 'Abstract function.' );
  1872. }
  1873. }
  1874. /**
  1875. * Class for representing a constant value in the shader.
  1876. *
  1877. * @augments InputNode
  1878. */
  1879. class ConstNode extends InputNode {
  1880. static get type() {
  1881. return 'ConstNode';
  1882. }
  1883. /**
  1884. * Constructs a new input node.
  1885. *
  1886. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1887. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1888. */
  1889. constructor( value, nodeType = null ) {
  1890. super( value, nodeType );
  1891. /**
  1892. * This flag can be used for type testing.
  1893. *
  1894. * @type {Boolean}
  1895. * @readonly
  1896. * @default true
  1897. */
  1898. this.isConstNode = true;
  1899. }
  1900. /**
  1901. * Generates the shader string of the value with the current node builder.
  1902. *
  1903. * @param {NodeBuilder} builder - The current node builder.
  1904. * @return {String} The generated value as a shader string.
  1905. */
  1906. generateConst( builder ) {
  1907. return builder.generateConst( this.getNodeType( builder ), this.value );
  1908. }
  1909. generate( builder, output ) {
  1910. const type = this.getNodeType( builder );
  1911. return builder.format( this.generateConst( builder ), type, output );
  1912. }
  1913. }
  1914. /** @module TSLCore **/
  1915. let currentStack = null;
  1916. const NodeElements = new Map();
  1917. function addMethodChaining( name, nodeElement ) {
  1918. if ( NodeElements.has( name ) ) {
  1919. console.warn( `Redefinition of method chaining ${ name }` );
  1920. return;
  1921. }
  1922. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1923. NodeElements.set( name, nodeElement );
  1924. }
  1925. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1926. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1927. const shaderNodeHandler = {
  1928. setup( NodeClosure, params ) {
  1929. const inputs = params.shift();
  1930. return NodeClosure( nodeObjects( inputs ), ...params );
  1931. },
  1932. get( node, prop, nodeObj ) {
  1933. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1934. if ( node.isStackNode !== true && prop === 'assign' ) {
  1935. return ( ...params ) => {
  1936. currentStack.assign( nodeObj, ...params );
  1937. return nodeObj;
  1938. };
  1939. } else if ( NodeElements.has( prop ) ) {
  1940. const nodeElement = NodeElements.get( prop );
  1941. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1942. } else if ( prop === 'self' ) {
  1943. return node;
  1944. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1945. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1946. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1947. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1948. // accessing properties ( swizzle )
  1949. prop = parseSwizzle( prop );
  1950. return nodeObject( new SplitNode( nodeObj, prop ) );
  1951. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1952. // set properties ( swizzle ) and sort to xyzw sequence
  1953. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1954. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1955. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1956. // set properties ( swizzle ) and sort to xyzw sequence
  1957. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1958. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1959. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1960. // accessing property
  1961. if ( prop === 'width' ) prop = 'x';
  1962. else if ( prop === 'height' ) prop = 'y';
  1963. else if ( prop === 'depth' ) prop = 'z';
  1964. return nodeObject( new SplitNode( node, prop ) );
  1965. } else if ( /^\d+$/.test( prop ) === true ) {
  1966. // accessing array
  1967. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1968. }
  1969. }
  1970. return Reflect.get( node, prop, nodeObj );
  1971. },
  1972. set( node, prop, value, nodeObj ) {
  1973. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1974. // setting properties
  1975. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1976. nodeObj[ prop ].assign( value );
  1977. return true;
  1978. }
  1979. }
  1980. return Reflect.set( node, prop, value, nodeObj );
  1981. }
  1982. };
  1983. const nodeObjectsCacheMap = new WeakMap();
  1984. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1985. const ShaderNodeObject = function ( obj, altType = null ) {
  1986. const type = getValueType( obj );
  1987. if ( type === 'node' ) {
  1988. let nodeObject = nodeObjectsCacheMap.get( obj );
  1989. if ( nodeObject === undefined ) {
  1990. nodeObject = new Proxy( obj, shaderNodeHandler );
  1991. nodeObjectsCacheMap.set( obj, nodeObject );
  1992. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1993. }
  1994. return nodeObject;
  1995. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1996. return nodeObject( getConstNode( obj, altType ) );
  1997. } else if ( type === 'shader' ) {
  1998. return Fn( obj );
  1999. }
  2000. return obj;
  2001. };
  2002. const ShaderNodeObjects = function ( objects, altType = null ) {
  2003. for ( const name in objects ) {
  2004. objects[ name ] = nodeObject( objects[ name ], altType );
  2005. }
  2006. return objects;
  2007. };
  2008. const ShaderNodeArray = function ( array, altType = null ) {
  2009. const len = array.length;
  2010. for ( let i = 0; i < len; i ++ ) {
  2011. array[ i ] = nodeObject( array[ i ], altType );
  2012. }
  2013. return array;
  2014. };
  2015. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2016. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2017. if ( scope === null ) {
  2018. return ( ...params ) => {
  2019. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2020. };
  2021. } else if ( factor !== null ) {
  2022. factor = nodeObject( factor );
  2023. return ( ...params ) => {
  2024. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2025. };
  2026. } else {
  2027. return ( ...params ) => {
  2028. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2029. };
  2030. }
  2031. };
  2032. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2033. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2034. };
  2035. class ShaderCallNodeInternal extends Node {
  2036. constructor( shaderNode, inputNodes ) {
  2037. super();
  2038. this.shaderNode = shaderNode;
  2039. this.inputNodes = inputNodes;
  2040. }
  2041. getNodeType( builder ) {
  2042. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2043. }
  2044. call( builder ) {
  2045. const { shaderNode, inputNodes } = this;
  2046. const properties = builder.getNodeProperties( shaderNode );
  2047. if ( properties.onceOutput ) return properties.onceOutput;
  2048. //
  2049. let result = null;
  2050. if ( shaderNode.layout ) {
  2051. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2052. if ( functionNodesCacheMap === undefined ) {
  2053. functionNodesCacheMap = new WeakMap();
  2054. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2055. }
  2056. let functionNode = functionNodesCacheMap.get( shaderNode );
  2057. if ( functionNode === undefined ) {
  2058. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2059. functionNodesCacheMap.set( shaderNode, functionNode );
  2060. }
  2061. if ( builder.currentFunctionNode !== null ) {
  2062. builder.currentFunctionNode.includes.push( functionNode );
  2063. }
  2064. result = nodeObject( functionNode.call( inputNodes ) );
  2065. } else {
  2066. const jsFunc = shaderNode.jsFunc;
  2067. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2068. result = nodeObject( outputNode );
  2069. }
  2070. if ( shaderNode.once ) {
  2071. properties.onceOutput = result;
  2072. }
  2073. return result;
  2074. }
  2075. getOutputNode( builder ) {
  2076. const properties = builder.getNodeProperties( this );
  2077. if ( properties.outputNode === null ) {
  2078. properties.outputNode = this.setupOutput( builder );
  2079. }
  2080. return properties.outputNode;
  2081. }
  2082. setup( builder ) {
  2083. return this.getOutputNode( builder );
  2084. }
  2085. setupOutput( builder ) {
  2086. builder.addStack();
  2087. builder.stack.outputNode = this.call( builder );
  2088. return builder.removeStack();
  2089. }
  2090. generate( builder, output ) {
  2091. const outputNode = this.getOutputNode( builder );
  2092. return outputNode.build( builder, output );
  2093. }
  2094. }
  2095. class ShaderNodeInternal extends Node {
  2096. constructor( jsFunc, nodeType ) {
  2097. super( nodeType );
  2098. this.jsFunc = jsFunc;
  2099. this.layout = null;
  2100. this.global = true;
  2101. this.once = false;
  2102. }
  2103. setLayout( layout ) {
  2104. this.layout = layout;
  2105. return this;
  2106. }
  2107. call( inputs = null ) {
  2108. nodeObjects( inputs );
  2109. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2110. }
  2111. setup() {
  2112. return this.call();
  2113. }
  2114. }
  2115. const bools = [ false, true ];
  2116. const uints = [ 0, 1, 2, 3 ];
  2117. const ints = [ -1, -2 ];
  2118. 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 ];
  2119. const boolsCacheMap = new Map();
  2120. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2121. const uintsCacheMap = new Map();
  2122. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2123. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2124. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2125. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2126. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2127. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2128. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2129. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2130. const getConstNode = ( value, type ) => {
  2131. if ( constNodesCacheMap.has( value ) ) {
  2132. return constNodesCacheMap.get( value );
  2133. } else if ( value.isNode === true ) {
  2134. return value;
  2135. } else {
  2136. return new ConstNode( value, type );
  2137. }
  2138. };
  2139. const safeGetNodeType = ( node ) => {
  2140. try {
  2141. return node.getNodeType();
  2142. } catch ( _ ) {
  2143. return undefined;
  2144. }
  2145. };
  2146. const ConvertType = function ( type, cacheMap = null ) {
  2147. return ( ...params ) => {
  2148. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2149. params = [ getValueFromType( type, ...params ) ];
  2150. }
  2151. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2152. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2153. }
  2154. if ( params.length === 1 ) {
  2155. const node = getConstNode( params[ 0 ], type );
  2156. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2157. return nodeObject( new ConvertNode( node, type ) );
  2158. }
  2159. const nodes = params.map( param => getConstNode( param ) );
  2160. return nodeObject( new JoinNode( nodes, type ) );
  2161. };
  2162. };
  2163. // exports
  2164. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2165. // utils
  2166. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2167. // shader node base
  2168. function ShaderNode( jsFunc, nodeType ) {
  2169. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2170. }
  2171. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2172. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2173. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2174. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2175. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2176. const Fn = ( jsFunc, nodeType ) => {
  2177. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2178. const fn = ( ...params ) => {
  2179. let inputs;
  2180. nodeObjects( params );
  2181. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2182. inputs = [ ...params ];
  2183. } else {
  2184. inputs = params[ 0 ];
  2185. }
  2186. return shaderNode.call( inputs );
  2187. };
  2188. fn.shaderNode = shaderNode;
  2189. fn.setLayout = ( layout ) => {
  2190. shaderNode.setLayout( layout );
  2191. return fn;
  2192. };
  2193. fn.once = () => {
  2194. shaderNode.once = true;
  2195. return fn;
  2196. };
  2197. return fn;
  2198. };
  2199. /**
  2200. * @function
  2201. * @deprecated since r168. Use {@link Fn} instead.
  2202. *
  2203. * @param {...any} params
  2204. * @returns {Function}
  2205. */
  2206. const tslFn = ( ...params ) => { // @deprecated, r168
  2207. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2208. return Fn( ...params );
  2209. };
  2210. //
  2211. addMethodChaining( 'toGlobal', ( node ) => {
  2212. node.global = true;
  2213. return node;
  2214. } );
  2215. //
  2216. const setCurrentStack = ( stack ) => {
  2217. currentStack = stack;
  2218. };
  2219. const getCurrentStack = () => currentStack;
  2220. const If = ( ...params ) => currentStack.If( ...params );
  2221. function append( node ) {
  2222. if ( currentStack ) currentStack.add( node );
  2223. return node;
  2224. }
  2225. addMethodChaining( 'append', append );
  2226. // types
  2227. const color = new ConvertType( 'color' );
  2228. const float = new ConvertType( 'float', cacheMaps.float );
  2229. const int = new ConvertType( 'int', cacheMaps.ints );
  2230. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2231. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2232. const vec2 = new ConvertType( 'vec2' );
  2233. const ivec2 = new ConvertType( 'ivec2' );
  2234. const uvec2 = new ConvertType( 'uvec2' );
  2235. const bvec2 = new ConvertType( 'bvec2' );
  2236. const vec3 = new ConvertType( 'vec3' );
  2237. const ivec3 = new ConvertType( 'ivec3' );
  2238. const uvec3 = new ConvertType( 'uvec3' );
  2239. const bvec3 = new ConvertType( 'bvec3' );
  2240. const vec4 = new ConvertType( 'vec4' );
  2241. const ivec4 = new ConvertType( 'ivec4' );
  2242. const uvec4 = new ConvertType( 'uvec4' );
  2243. const bvec4 = new ConvertType( 'bvec4' );
  2244. const mat2 = new ConvertType( 'mat2' );
  2245. const mat3 = new ConvertType( 'mat3' );
  2246. const mat4 = new ConvertType( 'mat4' );
  2247. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2248. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2249. addMethodChaining( 'toColor', color );
  2250. addMethodChaining( 'toFloat', float );
  2251. addMethodChaining( 'toInt', int );
  2252. addMethodChaining( 'toUint', uint );
  2253. addMethodChaining( 'toBool', bool );
  2254. addMethodChaining( 'toVec2', vec2 );
  2255. addMethodChaining( 'toIVec2', ivec2 );
  2256. addMethodChaining( 'toUVec2', uvec2 );
  2257. addMethodChaining( 'toBVec2', bvec2 );
  2258. addMethodChaining( 'toVec3', vec3 );
  2259. addMethodChaining( 'toIVec3', ivec3 );
  2260. addMethodChaining( 'toUVec3', uvec3 );
  2261. addMethodChaining( 'toBVec3', bvec3 );
  2262. addMethodChaining( 'toVec4', vec4 );
  2263. addMethodChaining( 'toIVec4', ivec4 );
  2264. addMethodChaining( 'toUVec4', uvec4 );
  2265. addMethodChaining( 'toBVec4', bvec4 );
  2266. addMethodChaining( 'toMat2', mat2 );
  2267. addMethodChaining( 'toMat3', mat3 );
  2268. addMethodChaining( 'toMat4', mat4 );
  2269. // basic nodes
  2270. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2271. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2272. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2273. addMethodChaining( 'element', element );
  2274. addMethodChaining( 'convert', convert );
  2275. /** @module UniformGroupNode **/
  2276. /**
  2277. * This node can be used to group single instances of {@link UniformNode}
  2278. * and manage them as a uniform buffer.
  2279. *
  2280. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2281. * will be used when defining the {@link UniformNode#groupNode} property.
  2282. *
  2283. * - `objectGroup`: Uniform buffer per object.
  2284. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2285. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2286. *
  2287. * @augments Node
  2288. */
  2289. class UniformGroupNode extends Node {
  2290. static get type() {
  2291. return 'UniformGroupNode';
  2292. }
  2293. /**
  2294. * Constructs a new uniform group node.
  2295. *
  2296. * @param {String} name - The name of the uniform group node.
  2297. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2298. * @param {Number} [order=1] - Influences the internal sorting.
  2299. */
  2300. constructor( name, shared = false, order = 1 ) {
  2301. super( 'string' );
  2302. /**
  2303. * The name of the uniform group node.
  2304. *
  2305. * @type {String}
  2306. */
  2307. this.name = name;
  2308. /**
  2309. * Whether this uniform group node is shared or not.
  2310. *
  2311. * @type {Boolean}
  2312. * @default false
  2313. */
  2314. this.shared = shared;
  2315. /**
  2316. * Influences the internal sorting.
  2317. * TODO: Add details when this property should be changed.
  2318. *
  2319. * @type {Number}
  2320. * @default 1
  2321. */
  2322. this.order = order;
  2323. /**
  2324. * This flag can be used for type testing.
  2325. *
  2326. * @type {Boolean}
  2327. * @readonly
  2328. * @default true
  2329. */
  2330. this.isUniformGroup = true;
  2331. }
  2332. serialize( data ) {
  2333. super.serialize( data );
  2334. data.name = this.name;
  2335. data.version = this.version;
  2336. data.shared = this.shared;
  2337. }
  2338. deserialize( data ) {
  2339. super.deserialize( data );
  2340. this.name = data.name;
  2341. this.version = data.version;
  2342. this.shared = data.shared;
  2343. }
  2344. }
  2345. /**
  2346. * TSL function for creating a uniform group node with the given name.
  2347. *
  2348. * @function
  2349. * @param {String} name - The name of the uniform group node.
  2350. * @returns {UniformGroupNode}
  2351. */
  2352. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2353. /**
  2354. * TSL function for creating a shared uniform group node with the given name and order.
  2355. *
  2356. * @function
  2357. * @param {String} name - The name of the uniform group node.
  2358. * @param {Number} [order=0] - Influences the internal sorting.
  2359. * @returns {UniformGroupNode}
  2360. */
  2361. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2362. /**
  2363. * TSL object that represents a shared uniform group node which is updated once per frame.
  2364. *
  2365. * @type {UniformGroupNode}
  2366. */
  2367. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2368. /**
  2369. * TSL object that represents a shared uniform group node which is updated once per render.
  2370. *
  2371. * @type {UniformGroupNode}
  2372. */
  2373. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2374. /**
  2375. * TSL object that represents a uniform group node which is updated once per object.
  2376. *
  2377. * @type {UniformGroupNode}
  2378. */
  2379. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2380. /** @module UniformNode **/
  2381. /**
  2382. * Class for representing a uniform.
  2383. *
  2384. * @augments InputNode
  2385. */
  2386. class UniformNode extends InputNode {
  2387. static get type() {
  2388. return 'UniformNode';
  2389. }
  2390. /**
  2391. * Constructs a new uniform node.
  2392. *
  2393. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2394. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2395. */
  2396. constructor( value, nodeType = null ) {
  2397. super( value, nodeType );
  2398. /**
  2399. * This flag can be used for type testing.
  2400. *
  2401. * @type {Boolean}
  2402. * @readonly
  2403. * @default true
  2404. */
  2405. this.isUniformNode = true;
  2406. /**
  2407. * The name or label of the uniform.
  2408. *
  2409. * @type {String}
  2410. * @default ''
  2411. */
  2412. this.name = '';
  2413. /**
  2414. * The uniform group of this uniform. By default, uniforms are
  2415. * managed per object but they might belong to a shared group
  2416. * which is updated per frame or render call.
  2417. *
  2418. * @type {UniformGroupNode}
  2419. */
  2420. this.groupNode = objectGroup;
  2421. }
  2422. /**
  2423. * Sets the {@link UniformNode#name} property.
  2424. *
  2425. * @param {String} name - The name of the uniform.
  2426. * @return {UniformNode} A reference to this node.
  2427. */
  2428. label( name ) {
  2429. this.name = name;
  2430. return this;
  2431. }
  2432. /**
  2433. * Sets the {@link UniformNode#groupNode} property.
  2434. *
  2435. * @param {UniformGroupNode} group - The uniform group.
  2436. * @return {UniformNode} A reference to this node.
  2437. */
  2438. setGroup( group ) {
  2439. this.groupNode = group;
  2440. return this;
  2441. }
  2442. /**
  2443. * Returns the {@link UniformNode#groupNode}.
  2444. *
  2445. * @return {UniformGroupNode} The uniform group.
  2446. */
  2447. getGroup() {
  2448. return this.groupNode;
  2449. }
  2450. /**
  2451. * By default, this method returns the result of {@link Node#getHash} but derived
  2452. * classes might overwrite this method with a different implementation.
  2453. *
  2454. * @param {NodeBuilder} builder - The current node builder.
  2455. * @return {String} The uniform hash.
  2456. */
  2457. getUniformHash( builder ) {
  2458. return this.getHash( builder );
  2459. }
  2460. onUpdate( callback, updateType ) {
  2461. const self = this.getSelf();
  2462. callback = callback.bind( self );
  2463. return super.onUpdate( ( frame ) => {
  2464. const value = callback( frame, self );
  2465. if ( value !== undefined ) {
  2466. this.value = value;
  2467. }
  2468. }, updateType );
  2469. }
  2470. generate( builder, output ) {
  2471. const type = this.getNodeType( builder );
  2472. const hash = this.getUniformHash( builder );
  2473. let sharedNode = builder.getNodeFromHash( hash );
  2474. if ( sharedNode === undefined ) {
  2475. builder.setHashNode( this, hash );
  2476. sharedNode = this;
  2477. }
  2478. const sharedNodeType = sharedNode.getInputType( builder );
  2479. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2480. const propertyName = builder.getPropertyName( nodeUniform );
  2481. if ( builder.context.label !== undefined ) delete builder.context.label;
  2482. return builder.format( propertyName, type, output );
  2483. }
  2484. }
  2485. /**
  2486. * TSL function for creating a uniform node.
  2487. *
  2488. * @function
  2489. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2490. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2491. * @returns {UniformNode}
  2492. */
  2493. const uniform = ( arg1, arg2 ) => {
  2494. const nodeType = getConstNodeType( arg2 || arg1 );
  2495. // @TODO: get ConstNode from .traverse() in the future
  2496. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2497. return nodeObject( new UniformNode( value, nodeType ) );
  2498. };
  2499. /** @module PropertyNode **/
  2500. /**
  2501. * This class represents a shader property. It can be used
  2502. * to explicitly define a property and assign a value to it.
  2503. *
  2504. * ```js
  2505. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2506. *```
  2507. * `PropertyNode` is used by the engine to predefined common material properties
  2508. * for TSL code.
  2509. *
  2510. * @augments Node
  2511. */
  2512. class PropertyNode extends Node {
  2513. static get type() {
  2514. return 'PropertyNode';
  2515. }
  2516. /**
  2517. * Constructs a new property node.
  2518. *
  2519. * @param {String} nodeType - The type of the node.
  2520. * @param {String?} [name=null] - The name of the property in the shader.
  2521. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2522. */
  2523. constructor( nodeType, name = null, varying = false ) {
  2524. super( nodeType );
  2525. /**
  2526. * The name of the property in the shader. If no name is defined,
  2527. * the node system auto-generates one.
  2528. *
  2529. * @type {String?}
  2530. * @default null
  2531. */
  2532. this.name = name;
  2533. /**
  2534. * Whether this property is a varying or not.
  2535. *
  2536. * @type {Boolean}
  2537. * @default false
  2538. */
  2539. this.varying = varying;
  2540. /**
  2541. * This flag can be used for type testing.
  2542. *
  2543. * @type {Boolean}
  2544. * @readonly
  2545. * @default true
  2546. */
  2547. this.isPropertyNode = true;
  2548. }
  2549. getHash( builder ) {
  2550. return this.name || super.getHash( builder );
  2551. }
  2552. /**
  2553. * The method is overwritten so it always returns `true`.
  2554. *
  2555. * @param {NodeBuilder} builder - The current node builder.
  2556. * @return {Boolean} Whether this node is global or not.
  2557. */
  2558. isGlobal( /*builder*/ ) {
  2559. return true;
  2560. }
  2561. generate( builder ) {
  2562. let nodeVar;
  2563. if ( this.varying === true ) {
  2564. nodeVar = builder.getVaryingFromNode( this, this.name );
  2565. nodeVar.needsInterpolation = true;
  2566. } else {
  2567. nodeVar = builder.getVarFromNode( this, this.name );
  2568. }
  2569. return builder.getPropertyName( nodeVar );
  2570. }
  2571. }
  2572. /**
  2573. * TSL function for creating a property node.
  2574. *
  2575. * @function
  2576. * @param {String} type - The type of the node.
  2577. * @param {String?} [name=null] - The name of the property in the shader.
  2578. * @returns {PropertyNode}
  2579. */
  2580. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2581. /**
  2582. * TSL function for creating a varying property node.
  2583. *
  2584. * @function
  2585. * @param {String} type - The type of the node.
  2586. * @param {String?} [name=null] - The name of the varying in the shader.
  2587. * @returns {PropertyNode}
  2588. */
  2589. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2590. /**
  2591. * TSL object that represents the shader variable `DiffuseColor`.
  2592. *
  2593. * @type {PropertyNode<vec4>}
  2594. */
  2595. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2596. /**
  2597. * TSL object that represents the shader variable `EmissiveColor`.
  2598. *
  2599. * @type {PropertyNode<vec3>}
  2600. */
  2601. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2602. /**
  2603. * TSL object that represents the shader variable `Roughness`.
  2604. *
  2605. * @type {PropertyNode<float>}
  2606. */
  2607. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2608. /**
  2609. * TSL object that represents the shader variable `Metalness`.
  2610. *
  2611. * @type {PropertyNode<float>}
  2612. */
  2613. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2614. /**
  2615. * TSL object that represents the shader variable `Clearcoat`.
  2616. *
  2617. * @type {PropertyNode<float>}
  2618. */
  2619. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2620. /**
  2621. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2622. *
  2623. * @type {PropertyNode<float>}
  2624. */
  2625. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2626. /**
  2627. * TSL object that represents the shader variable `Sheen`.
  2628. *
  2629. * @type {PropertyNode<vec3>}
  2630. */
  2631. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2632. /**
  2633. * TSL object that represents the shader variable `SheenRoughness`.
  2634. *
  2635. * @type {PropertyNode<float>}
  2636. */
  2637. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2638. /**
  2639. * TSL object that represents the shader variable `Iridescence`.
  2640. *
  2641. * @type {PropertyNode<float>}
  2642. */
  2643. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2644. /**
  2645. * TSL object that represents the shader variable `IridescenceIOR`.
  2646. *
  2647. * @type {PropertyNode<float>}
  2648. */
  2649. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2650. /**
  2651. * TSL object that represents the shader variable `IridescenceThickness`.
  2652. *
  2653. * @type {PropertyNode<float>}
  2654. */
  2655. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2656. /**
  2657. * TSL object that represents the shader variable `AlphaT`.
  2658. *
  2659. * @type {PropertyNode<float>}
  2660. */
  2661. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2662. /**
  2663. * TSL object that represents the shader variable `Anisotropy`.
  2664. *
  2665. * @type {PropertyNode<float>}
  2666. */
  2667. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2668. /**
  2669. * TSL object that represents the shader variable `AnisotropyT`.
  2670. *
  2671. * @type {PropertyNode<vec3>}
  2672. */
  2673. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2674. /**
  2675. * TSL object that represents the shader variable `AnisotropyB`.
  2676. *
  2677. * @type {PropertyNode<vec3>}
  2678. */
  2679. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2680. /**
  2681. * TSL object that represents the shader variable `SpecularColor`.
  2682. *
  2683. * @type {PropertyNode<color>}
  2684. */
  2685. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2686. /**
  2687. * TSL object that represents the shader variable `SpecularF90`.
  2688. *
  2689. * @type {PropertyNode<float>}
  2690. */
  2691. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2692. /**
  2693. * TSL object that represents the shader variable `Shininess`.
  2694. *
  2695. * @type {PropertyNode<float>}
  2696. */
  2697. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2698. /**
  2699. * TSL object that represents the shader variable `Output`.
  2700. *
  2701. * @type {PropertyNode<vec4>}
  2702. */
  2703. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2704. /**
  2705. * TSL object that represents the shader variable `dashSize`.
  2706. *
  2707. * @type {PropertyNode<float>}
  2708. */
  2709. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2710. /**
  2711. * TSL object that represents the shader variable `gapSize`.
  2712. *
  2713. * @type {PropertyNode<float>}
  2714. */
  2715. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2716. /**
  2717. * TSL object that represents the shader variable `pointWidth`.
  2718. *
  2719. * @type {PropertyNode<float>}
  2720. */
  2721. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2722. /**
  2723. * TSL object that represents the shader variable `IOR`.
  2724. *
  2725. * @type {PropertyNode<float>}
  2726. */
  2727. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2728. /**
  2729. * TSL object that represents the shader variable `Transmission`.
  2730. *
  2731. * @type {PropertyNode<float>}
  2732. */
  2733. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2734. /**
  2735. * TSL object that represents the shader variable `Thickness`.
  2736. *
  2737. * @type {PropertyNode<float>}
  2738. */
  2739. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2740. /**
  2741. * TSL object that represents the shader variable `AttenuationDistance`.
  2742. *
  2743. * @type {PropertyNode<float>}
  2744. */
  2745. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2746. /**
  2747. * TSL object that represents the shader variable `AttenuationColor`.
  2748. *
  2749. * @type {PropertyNode<color>}
  2750. */
  2751. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2752. /**
  2753. * TSL object that represents the shader variable `Dispersion`.
  2754. *
  2755. * @type {PropertyNode<float>}
  2756. */
  2757. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2758. /** @module AssignNode **/
  2759. /**
  2760. * These node represents an assign operation. Meaning a node is assigned
  2761. * to another node.
  2762. *
  2763. * @augments TempNode
  2764. */
  2765. class AssignNode extends TempNode {
  2766. static get type() {
  2767. return 'AssignNode';
  2768. }
  2769. /**
  2770. * Constructs a new assign node.
  2771. *
  2772. * @param {Node} targetNode - The target node.
  2773. * @param {Node} sourceNode - The source type.
  2774. */
  2775. constructor( targetNode, sourceNode ) {
  2776. super();
  2777. /**
  2778. * The target node.
  2779. *
  2780. * @type {Node}
  2781. */
  2782. this.targetNode = targetNode;
  2783. /**
  2784. * The source node.
  2785. *
  2786. * @type {Node}
  2787. */
  2788. this.sourceNode = sourceNode;
  2789. }
  2790. /**
  2791. * Whether this node is used more than once in context of other nodes. This method
  2792. * is overwritten since it always returns `false` (assigns are unique).
  2793. *
  2794. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2795. */
  2796. hasDependencies() {
  2797. return false;
  2798. }
  2799. getNodeType( builder, output ) {
  2800. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2801. }
  2802. /**
  2803. * Whether a split is required when assigning source to target. This can happen when the component length of
  2804. * target and source data type does not match.
  2805. *
  2806. * @param {NodeBuilder} builder - The current node builder.
  2807. * @return {Boolean} Whether a split is required when assigning source to target.
  2808. */
  2809. needsSplitAssign( builder ) {
  2810. const { targetNode } = this;
  2811. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2812. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2813. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2814. return assignDifferentVector;
  2815. }
  2816. return false;
  2817. }
  2818. generate( builder, output ) {
  2819. const { targetNode, sourceNode } = this;
  2820. const needsSplitAssign = this.needsSplitAssign( builder );
  2821. const targetType = targetNode.getNodeType( builder );
  2822. const target = targetNode.context( { assign: true } ).build( builder );
  2823. const source = sourceNode.build( builder, targetType );
  2824. const sourceType = sourceNode.getNodeType( builder );
  2825. const nodeData = builder.getDataFromNode( this );
  2826. //
  2827. let snippet;
  2828. if ( nodeData.initialized === true ) {
  2829. if ( output !== 'void' ) {
  2830. snippet = target;
  2831. }
  2832. } else if ( needsSplitAssign ) {
  2833. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2834. const sourceProperty = builder.getPropertyName( sourceVar );
  2835. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2836. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2837. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2838. const component = targetNode.components[ i ];
  2839. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2840. }
  2841. if ( output !== 'void' ) {
  2842. snippet = target;
  2843. }
  2844. } else {
  2845. snippet = `${ target } = ${ source }`;
  2846. if ( output === 'void' || sourceType === 'void' ) {
  2847. builder.addLineFlowCode( snippet, this );
  2848. if ( output !== 'void' ) {
  2849. snippet = target;
  2850. }
  2851. }
  2852. }
  2853. nodeData.initialized = true;
  2854. return builder.format( snippet, targetType, output );
  2855. }
  2856. }
  2857. /**
  2858. * TSL function for creating an assign node.
  2859. *
  2860. * @function
  2861. * @param {Node} targetNode - The target node.
  2862. * @param {Node} sourceNode - The source type.
  2863. * @returns {AssignNode}
  2864. */
  2865. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2866. addMethodChaining( 'assign', assign );
  2867. /**
  2868. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2869. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2870. * this logic.
  2871. *
  2872. * @augments TempNode
  2873. */
  2874. class FunctionCallNode extends TempNode {
  2875. static get type() {
  2876. return 'FunctionCallNode';
  2877. }
  2878. /**
  2879. * Constructs a new function call node.
  2880. *
  2881. * @param {FunctionNode?} functionNode - The function node.
  2882. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2883. */
  2884. constructor( functionNode = null, parameters = {} ) {
  2885. super();
  2886. /**
  2887. * The function node.
  2888. *
  2889. * @type {FunctionNode}
  2890. * @default null
  2891. */
  2892. this.functionNode = functionNode;
  2893. /**
  2894. * The parameters of the function call.
  2895. *
  2896. * @type {Object<String, Node>}
  2897. * @default {}
  2898. */
  2899. this.parameters = parameters;
  2900. }
  2901. /**
  2902. * Sets the parameters of the function call node.
  2903. *
  2904. * @param {Object<String, Node>} parameters - The parameters to set.
  2905. * @return {FunctionCallNode} A reference to this node.
  2906. */
  2907. setParameters( parameters ) {
  2908. this.parameters = parameters;
  2909. return this;
  2910. }
  2911. /**
  2912. * Returns the parameters of the function call node.
  2913. *
  2914. * @return {Object<String, Node>} The parameters of this node.
  2915. */
  2916. getParameters() {
  2917. return this.parameters;
  2918. }
  2919. getNodeType( builder ) {
  2920. return this.functionNode.getNodeType( builder );
  2921. }
  2922. generate( builder ) {
  2923. const params = [];
  2924. const functionNode = this.functionNode;
  2925. const inputs = functionNode.getInputs( builder );
  2926. const parameters = this.parameters;
  2927. const generateInput = ( node, inputNode ) => {
  2928. const type = inputNode.type;
  2929. const pointer = type === 'pointer';
  2930. let output;
  2931. if ( pointer ) output = '&' + node.build( builder );
  2932. else output = node.build( builder, type );
  2933. return output;
  2934. };
  2935. if ( Array.isArray( parameters ) ) {
  2936. for ( let i = 0; i < parameters.length; i ++ ) {
  2937. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2938. }
  2939. } else {
  2940. for ( const inputNode of inputs ) {
  2941. const node = parameters[ inputNode.name ];
  2942. if ( node !== undefined ) {
  2943. params.push( generateInput( node, inputNode ) );
  2944. } else {
  2945. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2946. }
  2947. }
  2948. }
  2949. const functionName = functionNode.build( builder, 'property' );
  2950. return `${functionName}( ${params.join( ', ' )} )`;
  2951. }
  2952. }
  2953. const call = ( func, ...params ) => {
  2954. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2955. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2956. };
  2957. addMethodChaining( 'call', call );
  2958. /** @module OperatorNode **/
  2959. /**
  2960. * This node represents basic mathematical and logical operations like addition,
  2961. * subtraction or comparisons (e.g. `equal()`).
  2962. *
  2963. * @augments TempNode
  2964. */
  2965. class OperatorNode extends TempNode {
  2966. static get type() {
  2967. return 'OperatorNode';
  2968. }
  2969. /**
  2970. * Constructs a new operator node.
  2971. *
  2972. * @param {String} op - The operator.
  2973. * @param {Node} aNode - The first input.
  2974. * @param {Node} bNode - The second input.
  2975. * @param {...Node} params - Additional input parameters.
  2976. */
  2977. constructor( op, aNode, bNode, ...params ) {
  2978. super();
  2979. if ( params.length > 0 ) {
  2980. let finalOp = new OperatorNode( op, aNode, bNode );
  2981. for ( let i = 0; i < params.length - 1; i ++ ) {
  2982. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2983. }
  2984. aNode = finalOp;
  2985. bNode = params[ params.length - 1 ];
  2986. }
  2987. /**
  2988. * The operator.
  2989. *
  2990. * @type {String}
  2991. */
  2992. this.op = op;
  2993. /**
  2994. * The first input.
  2995. *
  2996. * @type {Node}
  2997. */
  2998. this.aNode = aNode;
  2999. /**
  3000. * The second input.
  3001. *
  3002. * @type {Node}
  3003. */
  3004. this.bNode = bNode;
  3005. /**
  3006. * This flag can be used for type testing.
  3007. *
  3008. * @type {Boolean}
  3009. * @readonly
  3010. * @default true
  3011. */
  3012. this.isOperatorNode = true;
  3013. }
  3014. /**
  3015. * This method is overwritten since the node type is inferred from the operator
  3016. * and the input node types.
  3017. *
  3018. * @param {NodeBuilder} builder - The current node builder.
  3019. * @param {String} output - The current output string.
  3020. * @return {String} The node type.
  3021. */
  3022. getNodeType( builder, output ) {
  3023. const op = this.op;
  3024. const aNode = this.aNode;
  3025. const bNode = this.bNode;
  3026. const typeA = aNode.getNodeType( builder );
  3027. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3028. if ( typeA === 'void' || typeB === 'void' ) {
  3029. return 'void';
  3030. } else if ( op === '%' ) {
  3031. return typeA;
  3032. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3033. return builder.getIntegerType( typeA );
  3034. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3035. return 'bool';
  3036. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3037. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3038. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3039. } else {
  3040. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3041. return typeB;
  3042. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3043. // matrix x vector
  3044. return builder.getVectorFromMatrix( typeA );
  3045. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3046. // vector x matrix
  3047. return builder.getVectorFromMatrix( typeB );
  3048. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3049. // anytype x anytype: use the greater length vector
  3050. return typeB;
  3051. }
  3052. return typeA;
  3053. }
  3054. }
  3055. generate( builder, output ) {
  3056. const op = this.op;
  3057. const aNode = this.aNode;
  3058. const bNode = this.bNode;
  3059. const type = this.getNodeType( builder, output );
  3060. let typeA = null;
  3061. let typeB = null;
  3062. if ( type !== 'void' ) {
  3063. typeA = aNode.getNodeType( builder );
  3064. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3065. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3066. if ( builder.isVector( typeA ) ) {
  3067. typeB = typeA;
  3068. } else if ( typeA !== typeB ) {
  3069. typeA = typeB = 'float';
  3070. }
  3071. } else if ( op === '>>' || op === '<<' ) {
  3072. typeA = type;
  3073. typeB = builder.changeComponentType( typeB, 'uint' );
  3074. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3075. // matrix x vector
  3076. typeB = builder.getVectorFromMatrix( typeA );
  3077. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3078. // vector x matrix
  3079. typeA = builder.getVectorFromMatrix( typeB );
  3080. } else {
  3081. // anytype x anytype
  3082. typeA = typeB = type;
  3083. }
  3084. } else {
  3085. typeA = typeB = type;
  3086. }
  3087. const a = aNode.build( builder, typeA );
  3088. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3089. const outputLength = builder.getTypeLength( output );
  3090. const fnOpSnippet = builder.getFunctionOperator( op );
  3091. if ( output !== 'void' ) {
  3092. if ( op === '<' && outputLength > 1 ) {
  3093. if ( builder.useComparisonMethod ) {
  3094. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3095. } else {
  3096. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3097. }
  3098. } else if ( op === '<=' && outputLength > 1 ) {
  3099. if ( builder.useComparisonMethod ) {
  3100. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3101. } else {
  3102. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3103. }
  3104. } else if ( op === '>' && outputLength > 1 ) {
  3105. if ( builder.useComparisonMethod ) {
  3106. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3107. } else {
  3108. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3109. }
  3110. } else if ( op === '>=' && outputLength > 1 ) {
  3111. if ( builder.useComparisonMethod ) {
  3112. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3113. } else {
  3114. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3115. }
  3116. } else if ( op === '!' || op === '~' ) {
  3117. return builder.format( `(${op}${a})`, typeA, output );
  3118. } else if ( fnOpSnippet ) {
  3119. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3120. } else {
  3121. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3122. }
  3123. } else if ( typeA !== 'void' ) {
  3124. if ( fnOpSnippet ) {
  3125. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3126. } else {
  3127. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3128. }
  3129. }
  3130. }
  3131. serialize( data ) {
  3132. super.serialize( data );
  3133. data.op = this.op;
  3134. }
  3135. deserialize( data ) {
  3136. super.deserialize( data );
  3137. this.op = data.op;
  3138. }
  3139. }
  3140. /**
  3141. * Returns the addition of two or more value.
  3142. *
  3143. * @function
  3144. * @param {Node} aNode - The first input.
  3145. * @param {Node} bNode - The second input.
  3146. * @param {...Node} params - Additional input parameters.
  3147. * @returns {OperatorNode}
  3148. */
  3149. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3150. /**
  3151. * Returns the subtraction of two or more value.
  3152. *
  3153. * @function
  3154. * @param {Node} aNode - The first input.
  3155. * @param {Node} bNode - The second input.
  3156. * @param {...Node} params - Additional input parameters.
  3157. * @returns {OperatorNode}
  3158. */
  3159. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3160. /**
  3161. * Returns the multiplication of two or more value.
  3162. *
  3163. * @function
  3164. * @param {Node} aNode - The first input.
  3165. * @param {Node} bNode - The second input.
  3166. * @param {...Node} params - Additional input parameters.
  3167. * @returns {OperatorNode}
  3168. */
  3169. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3170. /**
  3171. * Returns the division of two or more value.
  3172. *
  3173. * @function
  3174. * @param {Node} aNode - The first input.
  3175. * @param {Node} bNode - The second input.
  3176. * @param {...Node} params - Additional input parameters.
  3177. * @returns {OperatorNode}
  3178. */
  3179. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3180. /**
  3181. * Computes the remainder of dividing the first node by the second, for integer values.
  3182. *
  3183. * @function
  3184. * @param {Node} aNode - The first input.
  3185. * @param {Node} bNode - The second input.
  3186. * @returns {OperatorNode}
  3187. */
  3188. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3189. /**
  3190. * Checks if two nodes are equal.
  3191. *
  3192. * @function
  3193. * @param {Node} aNode - The first input.
  3194. * @param {Node} bNode - The second input.
  3195. * @returns {OperatorNode}
  3196. */
  3197. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3198. /**
  3199. * Checks if two nodes are not equal.
  3200. *
  3201. * @function
  3202. * @param {Node} aNode - The first input.
  3203. * @param {Node} bNode - The second input.
  3204. * @returns {OperatorNode}
  3205. */
  3206. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3207. /**
  3208. * Checks if the first node is less than the second.
  3209. *
  3210. * @function
  3211. * @param {Node} aNode - The first input.
  3212. * @param {Node} bNode - The second input.
  3213. * @returns {OperatorNode}
  3214. */
  3215. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3216. /**
  3217. * Checks if the first node is greater than the second.
  3218. *
  3219. * @function
  3220. * @param {Node} aNode - The first input.
  3221. * @param {Node} bNode - The second input.
  3222. * @returns {OperatorNode}
  3223. */
  3224. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3225. /**
  3226. * Checks if the first node is less than or equal to the second.
  3227. *
  3228. * @function
  3229. * @param {Node} aNode - The first input.
  3230. * @param {Node} bNode - The second input.
  3231. * @returns {OperatorNode}
  3232. */
  3233. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3234. /**
  3235. * Checks if the first node is greater than or equal to the second.
  3236. *
  3237. * @function
  3238. * @param {Node} aNode - The first input.
  3239. * @param {Node} bNode - The second input.
  3240. * @returns {OperatorNode}
  3241. */
  3242. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3243. /**
  3244. * Performs logical AND on two nodes.
  3245. *
  3246. * @function
  3247. * @param {Node} aNode - The first input.
  3248. * @param {Node} bNode - The second input.
  3249. * @returns {OperatorNode}
  3250. */
  3251. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3252. /**
  3253. * Performs logical OR on two nodes.
  3254. *
  3255. * @function
  3256. * @param {Node} aNode - The first input.
  3257. * @param {Node} bNode - The second input.
  3258. * @returns {OperatorNode}
  3259. */
  3260. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3261. /**
  3262. * Performs logical NOT on a node.
  3263. *
  3264. * @function
  3265. * @param {Node} aNode - The first input.
  3266. * @param {Node} bNode - The second input.
  3267. * @returns {OperatorNode}
  3268. */
  3269. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3270. /**
  3271. * Performs logical XOR on two nodes.
  3272. *
  3273. * @function
  3274. * @param {Node} aNode - The first input.
  3275. * @param {Node} bNode - The second input.
  3276. * @returns {OperatorNode}
  3277. */
  3278. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3279. /**
  3280. * Performs bitwise AND on two nodes.
  3281. *
  3282. * @function
  3283. * @param {Node} aNode - The first input.
  3284. * @param {Node} bNode - The second input.
  3285. * @returns {OperatorNode}
  3286. */
  3287. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3288. /**
  3289. * Performs bitwise NOT on a node.
  3290. *
  3291. * @function
  3292. * @param {Node} aNode - The first input.
  3293. * @param {Node} bNode - The second input.
  3294. * @returns {OperatorNode}
  3295. */
  3296. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3297. /**
  3298. * Performs bitwise OR on two nodes.
  3299. *
  3300. * @function
  3301. * @param {Node} aNode - The first input.
  3302. * @param {Node} bNode - The second input.
  3303. * @returns {OperatorNode}
  3304. */
  3305. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3306. /**
  3307. * Performs bitwise XOR on two nodes.
  3308. *
  3309. * @function
  3310. * @param {Node} aNode - The first input.
  3311. * @param {Node} bNode - The second input.
  3312. * @returns {OperatorNode}
  3313. */
  3314. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3315. /**
  3316. * Shifts a node to the left.
  3317. *
  3318. * @function
  3319. * @param {Node} aNode - The node to shift.
  3320. * @param {Node} bNode - The value to shift.
  3321. * @returns {OperatorNode}
  3322. */
  3323. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3324. /**
  3325. * Shifts a node to the right.
  3326. *
  3327. * @function
  3328. * @param {Node} aNode - The node to shift.
  3329. * @param {Node} bNode - The value to shift.
  3330. * @returns {OperatorNode}
  3331. */
  3332. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3333. addMethodChaining( 'add', add );
  3334. addMethodChaining( 'sub', sub );
  3335. addMethodChaining( 'mul', mul );
  3336. addMethodChaining( 'div', div );
  3337. addMethodChaining( 'modInt', modInt );
  3338. addMethodChaining( 'equal', equal );
  3339. addMethodChaining( 'notEqual', notEqual );
  3340. addMethodChaining( 'lessThan', lessThan );
  3341. addMethodChaining( 'greaterThan', greaterThan );
  3342. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3343. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3344. addMethodChaining( 'and', and );
  3345. addMethodChaining( 'or', or );
  3346. addMethodChaining( 'not', not );
  3347. addMethodChaining( 'xor', xor );
  3348. addMethodChaining( 'bitAnd', bitAnd );
  3349. addMethodChaining( 'bitNot', bitNot );
  3350. addMethodChaining( 'bitOr', bitOr );
  3351. addMethodChaining( 'bitXor', bitXor );
  3352. addMethodChaining( 'shiftLeft', shiftLeft );
  3353. addMethodChaining( 'shiftRight', shiftRight );
  3354. /**
  3355. * @function
  3356. * @deprecated since r168. Use {@link modInt} instead.
  3357. *
  3358. * @param {...any} params
  3359. * @returns {Function}
  3360. */
  3361. const remainder = ( ...params ) => { // @deprecated, r168
  3362. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3363. return modInt( ...params );
  3364. };
  3365. addMethodChaining( 'remainder', remainder );
  3366. /** @module MathNode **/
  3367. /**
  3368. * This node represents a variety of mathematical methods available in shaders.
  3369. * They are divided into three categories:
  3370. *
  3371. * - Methods with one input like `sin`, `cos` or `normalize`.
  3372. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3373. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3374. *
  3375. * @augments TempNode
  3376. */
  3377. class MathNode extends TempNode {
  3378. static get type() {
  3379. return 'MathNode';
  3380. }
  3381. /**
  3382. * Constructs a new math node.
  3383. *
  3384. * @param {String} method - The method name.
  3385. * @param {Node} aNode - The first input.
  3386. * @param {Node?} [bNode=null] - The second input.
  3387. * @param {Node?} [cNode=null] - The third input.
  3388. */
  3389. constructor( method, aNode, bNode = null, cNode = null ) {
  3390. super();
  3391. /**
  3392. * The method name.
  3393. *
  3394. * @type {String}
  3395. */
  3396. this.method = method;
  3397. /**
  3398. * The first input.
  3399. *
  3400. * @type {Node}
  3401. */
  3402. this.aNode = aNode;
  3403. /**
  3404. * The second input.
  3405. *
  3406. * @type {Node?}
  3407. * @default null
  3408. */
  3409. this.bNode = bNode;
  3410. /**
  3411. * The third input.
  3412. *
  3413. * @type {Node?}
  3414. * @default null
  3415. */
  3416. this.cNode = cNode;
  3417. /**
  3418. * This flag can be used for type testing.
  3419. *
  3420. * @type {Boolean}
  3421. * @readonly
  3422. * @default true
  3423. */
  3424. this.isMathNode = true;
  3425. }
  3426. /**
  3427. * The input type is inferred from the node types of the input nodes.
  3428. *
  3429. * @param {NodeBuilder} builder - The current node builder.
  3430. * @return {String} The input type.
  3431. */
  3432. getInputType( builder ) {
  3433. const aType = this.aNode.getNodeType( builder );
  3434. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3435. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3436. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3437. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3438. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3439. if ( aLen > bLen && aLen > cLen ) {
  3440. return aType;
  3441. } else if ( bLen > cLen ) {
  3442. return bType;
  3443. } else if ( cLen > aLen ) {
  3444. return cType;
  3445. }
  3446. return aType;
  3447. }
  3448. /**
  3449. * The selected method as well as the input type determine the node type of this node.
  3450. *
  3451. * @param {NodeBuilder} builder - The current node builder.
  3452. * @return {String} The node type.
  3453. */
  3454. getNodeType( builder ) {
  3455. const method = this.method;
  3456. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3457. return 'float';
  3458. } else if ( method === MathNode.CROSS ) {
  3459. return 'vec3';
  3460. } else if ( method === MathNode.ALL ) {
  3461. return 'bool';
  3462. } else if ( method === MathNode.EQUALS ) {
  3463. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3464. } else if ( method === MathNode.MOD ) {
  3465. return this.aNode.getNodeType( builder );
  3466. } else {
  3467. return this.getInputType( builder );
  3468. }
  3469. }
  3470. generate( builder, output ) {
  3471. let method = this.method;
  3472. const type = this.getNodeType( builder );
  3473. const inputType = this.getInputType( builder );
  3474. const a = this.aNode;
  3475. const b = this.bNode;
  3476. const c = this.cNode;
  3477. const coordinateSystem = builder.renderer.coordinateSystem;
  3478. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3479. // dir can be either a direction vector or a normal vector
  3480. // upper-left 3x3 of matrix is assumed to be orthogonal
  3481. let tA = a;
  3482. let tB = b;
  3483. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3484. tB = vec4( vec3( tB ), 0.0 );
  3485. } else {
  3486. tA = vec4( vec3( tA ), 0.0 );
  3487. }
  3488. const mulNode = mul( tA, tB ).xyz;
  3489. return normalize( mulNode ).build( builder, output );
  3490. } else if ( method === MathNode.NEGATE ) {
  3491. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3492. } else if ( method === MathNode.ONE_MINUS ) {
  3493. return sub( 1.0, a ).build( builder, output );
  3494. } else if ( method === MathNode.RECIPROCAL ) {
  3495. return div( 1.0, a ).build( builder, output );
  3496. } else if ( method === MathNode.DIFFERENCE ) {
  3497. return abs( sub( a, b ) ).build( builder, output );
  3498. } else {
  3499. const params = [];
  3500. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3501. params.push(
  3502. a.build( builder, type ),
  3503. b.build( builder, type )
  3504. );
  3505. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3506. params.push(
  3507. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3508. b.build( builder, inputType )
  3509. );
  3510. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3511. params.push(
  3512. a.build( builder, inputType ),
  3513. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3514. );
  3515. } else if ( method === MathNode.REFRACT ) {
  3516. params.push(
  3517. a.build( builder, inputType ),
  3518. b.build( builder, inputType ),
  3519. c.build( builder, 'float' )
  3520. );
  3521. } else if ( method === MathNode.MIX ) {
  3522. params.push(
  3523. a.build( builder, inputType ),
  3524. b.build( builder, inputType ),
  3525. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3526. );
  3527. } else {
  3528. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3529. method = 'atan2';
  3530. }
  3531. params.push( a.build( builder, inputType ) );
  3532. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3533. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3534. }
  3535. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3536. }
  3537. }
  3538. serialize( data ) {
  3539. super.serialize( data );
  3540. data.method = this.method;
  3541. }
  3542. deserialize( data ) {
  3543. super.deserialize( data );
  3544. this.method = data.method;
  3545. }
  3546. }
  3547. // 1 input
  3548. MathNode.ALL = 'all';
  3549. MathNode.ANY = 'any';
  3550. MathNode.RADIANS = 'radians';
  3551. MathNode.DEGREES = 'degrees';
  3552. MathNode.EXP = 'exp';
  3553. MathNode.EXP2 = 'exp2';
  3554. MathNode.LOG = 'log';
  3555. MathNode.LOG2 = 'log2';
  3556. MathNode.SQRT = 'sqrt';
  3557. MathNode.INVERSE_SQRT = 'inversesqrt';
  3558. MathNode.FLOOR = 'floor';
  3559. MathNode.CEIL = 'ceil';
  3560. MathNode.NORMALIZE = 'normalize';
  3561. MathNode.FRACT = 'fract';
  3562. MathNode.SIN = 'sin';
  3563. MathNode.COS = 'cos';
  3564. MathNode.TAN = 'tan';
  3565. MathNode.ASIN = 'asin';
  3566. MathNode.ACOS = 'acos';
  3567. MathNode.ATAN = 'atan';
  3568. MathNode.ABS = 'abs';
  3569. MathNode.SIGN = 'sign';
  3570. MathNode.LENGTH = 'length';
  3571. MathNode.NEGATE = 'negate';
  3572. MathNode.ONE_MINUS = 'oneMinus';
  3573. MathNode.DFDX = 'dFdx';
  3574. MathNode.DFDY = 'dFdy';
  3575. MathNode.ROUND = 'round';
  3576. MathNode.RECIPROCAL = 'reciprocal';
  3577. MathNode.TRUNC = 'trunc';
  3578. MathNode.FWIDTH = 'fwidth';
  3579. MathNode.TRANSPOSE = 'transpose';
  3580. // 2 inputs
  3581. MathNode.BITCAST = 'bitcast';
  3582. MathNode.EQUALS = 'equals';
  3583. MathNode.MIN = 'min';
  3584. MathNode.MAX = 'max';
  3585. MathNode.MOD = 'mod';
  3586. MathNode.STEP = 'step';
  3587. MathNode.REFLECT = 'reflect';
  3588. MathNode.DISTANCE = 'distance';
  3589. MathNode.DIFFERENCE = 'difference';
  3590. MathNode.DOT = 'dot';
  3591. MathNode.CROSS = 'cross';
  3592. MathNode.POW = 'pow';
  3593. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3594. // 3 inputs
  3595. MathNode.MIX = 'mix';
  3596. MathNode.CLAMP = 'clamp';
  3597. MathNode.REFRACT = 'refract';
  3598. MathNode.SMOOTHSTEP = 'smoothstep';
  3599. MathNode.FACEFORWARD = 'faceforward';
  3600. // 1 inputs
  3601. /**
  3602. * A small value used to handle floating-point precision errors.
  3603. *
  3604. * @type {Node<float>}
  3605. */
  3606. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3607. /**
  3608. * Represents infinity.
  3609. *
  3610. * @type {Node<float>}
  3611. */
  3612. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3613. /**
  3614. * Represents PI.
  3615. *
  3616. * @type {Node<float>}
  3617. */
  3618. const PI = /*@__PURE__*/ float( Math.PI );
  3619. /**
  3620. * Represents PI * 2.
  3621. *
  3622. * @type {Node<float>}
  3623. */
  3624. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3625. /**
  3626. * Returns `true` if all components of `x` are `true`.
  3627. *
  3628. * @function
  3629. * @param {Node | Number} x - The parameter.
  3630. * @returns {Node<bool>}
  3631. */
  3632. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3633. /**
  3634. * Returns `true` if any components of `x` are `true`.
  3635. *
  3636. * @function
  3637. * @param {Node | Number} x - The parameter.
  3638. * @returns {Node<bool>}
  3639. */
  3640. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3641. /**
  3642. * Converts a quantity in degrees to radians.
  3643. *
  3644. * @function
  3645. * @param {Node | Number} x - The input in degrees.
  3646. * @returns {Node}
  3647. */
  3648. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3649. /**
  3650. * Convert a quantity in radians to degrees.
  3651. *
  3652. * @function
  3653. * @param {Node | Number} x - The input in radians.
  3654. * @returns {Node}
  3655. */
  3656. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3657. /**
  3658. * Returns the natural exponentiation of the parameter.
  3659. *
  3660. * @function
  3661. * @param {Node | Number} x - The parameter.
  3662. * @returns {Node}
  3663. */
  3664. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3665. /**
  3666. * Returns 2 raised to the power of the parameter.
  3667. *
  3668. * @function
  3669. * @param {Node | Number} x - The parameter.
  3670. * @returns {Node}
  3671. */
  3672. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3673. /**
  3674. * Returns the natural logarithm of the parameter.
  3675. *
  3676. * @function
  3677. * @param {Node | Number} x - The parameter.
  3678. * @returns {Node}
  3679. */
  3680. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3681. /**
  3682. * Returns the base 2 logarithm of the parameter.
  3683. *
  3684. * @function
  3685. * @param {Node | Number} x - The parameter.
  3686. * @returns {Node}
  3687. */
  3688. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3689. /**
  3690. * Returns the square root of the parameter.
  3691. *
  3692. * @function
  3693. * @param {Node | Number} x - The parameter.
  3694. * @returns {Node}
  3695. */
  3696. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3697. /**
  3698. * Returns the inverse of the square root of the parameter.
  3699. *
  3700. * @function
  3701. * @param {Node | Number} x - The parameter.
  3702. * @returns {Node}
  3703. */
  3704. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3705. /**
  3706. * Finds the nearest integer less than or equal to the parameter.
  3707. *
  3708. * @function
  3709. * @param {Node | Number} x - The parameter.
  3710. * @returns {Node}
  3711. */
  3712. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3713. /**
  3714. * Finds the nearest integer that is greater than or equal to the parameter.
  3715. *
  3716. * @function
  3717. * @param {Node | Number} x - The parameter.
  3718. * @returns {Node}
  3719. */
  3720. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3721. /**
  3722. * Calculates the unit vector in the same direction as the original vector.
  3723. *
  3724. * @function
  3725. * @param {Node} x - The input vector.
  3726. * @returns {Node}
  3727. */
  3728. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3729. /**
  3730. * Computes the fractional part of the parameter.
  3731. *
  3732. * @function
  3733. * @param {Node | Number} x - The parameter.
  3734. * @returns {Node}
  3735. */
  3736. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3737. /**
  3738. * Returns the sine of the parameter.
  3739. *
  3740. * @function
  3741. * @param {Node | Number} x - The parameter.
  3742. * @returns {Node}
  3743. */
  3744. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3745. /**
  3746. * Returns the cosine of the parameter.
  3747. *
  3748. * @function
  3749. * @param {Node | Number} x - The parameter.
  3750. * @returns {Node}
  3751. */
  3752. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3753. /**
  3754. * Returns the tangent of the parameter.
  3755. *
  3756. * @function
  3757. * @param {Node | Number} x - The parameter.
  3758. * @returns {Node}
  3759. */
  3760. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3761. /**
  3762. * Returns the arcsine of the parameter.
  3763. *
  3764. * @function
  3765. * @param {Node | Number} x - The parameter.
  3766. * @returns {Node}
  3767. */
  3768. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3769. /**
  3770. * Returns the arccosine of the parameter.
  3771. *
  3772. * @function
  3773. * @param {Node | Number} x - The parameter.
  3774. * @returns {Node}
  3775. */
  3776. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3777. /**
  3778. * Returns the arc-tangent of the parameter.
  3779. * If two parameters are provided, the result is `atan2(y/x)`.
  3780. *
  3781. * @function
  3782. * @param {Node | Number} y - The y parameter.
  3783. * @param {(Node | Number)?} x - The x parameter.
  3784. * @returns {Node}
  3785. */
  3786. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3787. /**
  3788. * Returns the absolute value of the parameter.
  3789. *
  3790. * @function
  3791. * @param {Node | Number} x - The parameter.
  3792. * @returns {Node}
  3793. */
  3794. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3795. /**
  3796. * Extracts the sign of the parameter.
  3797. *
  3798. * @function
  3799. * @param {Node | Number} x - The parameter.
  3800. * @returns {Node}
  3801. */
  3802. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3803. /**
  3804. * Calculates the length of a vector.
  3805. *
  3806. * @function
  3807. * @param {Node} x - The parameter.
  3808. * @returns {Node<float>}
  3809. */
  3810. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3811. /**
  3812. * Negates the value of the parameter (-x).
  3813. *
  3814. * @function
  3815. * @param {Node | Number} x - The parameter.
  3816. * @returns {Node}
  3817. */
  3818. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3819. /**
  3820. * Return `1` minus the parameter.
  3821. *
  3822. * @function
  3823. * @param {Node | Number} x - The parameter.
  3824. * @returns {Node}
  3825. */
  3826. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3827. /**
  3828. * Returns the partial derivative of the parameter with respect to x.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The parameter.
  3832. * @returns {Node}
  3833. */
  3834. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3835. /**
  3836. * Returns the partial derivative of the parameter with respect to y.
  3837. *
  3838. * @function
  3839. * @param {Node | Number} x - The parameter.
  3840. * @returns {Node}
  3841. */
  3842. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3843. /**
  3844. * Rounds the parameter to the nearest integer.
  3845. *
  3846. * @function
  3847. * @param {Node | Number} x - The parameter.
  3848. * @returns {Node}
  3849. */
  3850. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3851. /**
  3852. * Returns the reciprocal of the parameter `(1/x)`.
  3853. *
  3854. * @function
  3855. * @param {Node | Number} x - The parameter.
  3856. * @returns {Node}
  3857. */
  3858. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3859. /**
  3860. * Truncates the parameter, removing the fractional part.
  3861. *
  3862. * @function
  3863. * @param {Node | Number} x - The parameter.
  3864. * @returns {Node}
  3865. */
  3866. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3867. /**
  3868. * Returns the sum of the absolute derivatives in x and y.
  3869. *
  3870. * @function
  3871. * @param {Node | Number} x - The parameter.
  3872. * @returns {Node}
  3873. */
  3874. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3875. /**
  3876. * Returns the transpose of a matrix.
  3877. *
  3878. * @function
  3879. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3880. * @returns {Node}
  3881. */
  3882. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3883. // 2 inputs
  3884. /**
  3885. * Reinterpret the bit representation of a value in one type as a value in another type.
  3886. *
  3887. * @function
  3888. * @param {Node | Number} x - The parameter.
  3889. * @param {String} y - The new type.
  3890. * @returns {Node}
  3891. */
  3892. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3893. /**
  3894. * Returns `true` if `x` equals `y`.
  3895. *
  3896. * @function
  3897. * @param {Node | Number} x - The first parameter.
  3898. * @param {Node | Number} y - The second parameter.
  3899. * @returns {Node<bool>}
  3900. */
  3901. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3902. /**
  3903. * Returns the lesser of two values.
  3904. *
  3905. * @function
  3906. * @param {Node | Number} x - The y parameter.
  3907. * @param {Node | Number} y - The x parameter.
  3908. * @returns {Node}
  3909. */
  3910. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3911. /**
  3912. * Returns the greater of two values.
  3913. *
  3914. * @function
  3915. * @param {Node | Number} x - The y parameter.
  3916. * @param {Node | Number} y - The x parameter.
  3917. * @returns {Node}
  3918. */
  3919. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3920. /**
  3921. * Computes the remainder of dividing the first node by the second one.
  3922. *
  3923. * @function
  3924. * @param {Node | Number} x - The y parameter.
  3925. * @param {Node | Number} y - The x parameter.
  3926. * @returns {Node}
  3927. */
  3928. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3929. /**
  3930. * Generate a step function by comparing two values.
  3931. *
  3932. * @function
  3933. * @param {Node | Number} x - The y parameter.
  3934. * @param {Node | Number} y - The x parameter.
  3935. * @returns {Node}
  3936. */
  3937. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3938. /**
  3939. * Calculates the reflection direction for an incident vector.
  3940. *
  3941. * @function
  3942. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3943. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3944. * @returns {Node<vec2|vec3|vec4>}
  3945. */
  3946. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3947. /**
  3948. * Calculates the distance between two points.
  3949. *
  3950. * @function
  3951. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3952. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3953. * @returns {Node<float>}
  3954. */
  3955. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3956. /**
  3957. * Calculates the absolute difference between two values.
  3958. *
  3959. * @function
  3960. * @param {Node | Number} x - The first parameter.
  3961. * @param {Node | Number} y - The second parameter.
  3962. * @returns {Node}
  3963. */
  3964. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3965. /**
  3966. * Calculates the dot product of two vectors.
  3967. *
  3968. * @function
  3969. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3970. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3971. * @returns {Node<float>}
  3972. */
  3973. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3974. /**
  3975. * Calculates the cross product of two vectors.
  3976. *
  3977. * @function
  3978. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3979. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3980. * @returns {Node<vec2|vec3|vec4>}
  3981. */
  3982. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3983. /**
  3984. * Return the value of the first parameter raised to the power of the second one.
  3985. *
  3986. * @function
  3987. * @param {Node | Number} x - The first parameter.
  3988. * @param {Node | Number} y - The second parameter.
  3989. * @returns {Node}
  3990. */
  3991. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3992. /**
  3993. * Returns the square of the parameter.
  3994. *
  3995. * @function
  3996. * @param {Node | Number} x - The first parameter.
  3997. * @returns {Node}
  3998. */
  3999. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4000. /**
  4001. * Returns the cube of the parameter.
  4002. *
  4003. * @function
  4004. * @param {Node | Number} x - The first parameter.
  4005. * @returns {Node}
  4006. */
  4007. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4008. /**
  4009. * Returns the fourth power of the parameter.
  4010. *
  4011. * @function
  4012. * @param {Node | Number} x - The first parameter.
  4013. * @returns {Node}
  4014. */
  4015. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4016. /**
  4017. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4018. *
  4019. * @function
  4020. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4021. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4022. * @returns {Node}
  4023. */
  4024. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4025. /**
  4026. * Returns the cube root of a number.
  4027. *
  4028. * @function
  4029. * @param {Node | Number} a - The first parameter.
  4030. * @returns {Node}
  4031. */
  4032. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4033. /**
  4034. * Calculate the squared length of a vector.
  4035. *
  4036. * @function
  4037. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4038. * @returns {Node<float>}
  4039. */
  4040. const lengthSq = ( a ) => dot( a, a );
  4041. /**
  4042. * Linearly interpolates between two values.
  4043. *
  4044. * @function
  4045. * @param {Node | Number} a - The first parameter.
  4046. * @param {Node | Number} b - The second parameter.
  4047. * @param {Node | Number} t - The interpolation value.
  4048. * @returns {Node}
  4049. */
  4050. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4051. /**
  4052. * Constrains a value to lie between two further values.
  4053. *
  4054. * @function
  4055. * @param {Node | Number} value - The value to constrain.
  4056. * @param {Node | Number} [low=0] - The lower bound.
  4057. * @param {Node | Number} [high=1] - The upper bound.
  4058. * @returns {Node}
  4059. */
  4060. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4061. /**
  4062. * Constrains a value between `0` and `1`.
  4063. *
  4064. * @function
  4065. * @param {Node | Number} value - The value to constrain.
  4066. * @returns {Node}
  4067. */
  4068. const saturate = ( value ) => clamp( value );
  4069. /**
  4070. * Calculates the refraction direction for an incident vector.
  4071. *
  4072. * @function
  4073. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4074. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4075. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4076. * @returns {Node<vec2|vec3|vec4>}
  4077. */
  4078. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4079. /**
  4080. * Performs a Hermite interpolation between two values.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4084. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4085. * @param {Node | Number} x - The source value for interpolation.
  4086. * @returns {Node}
  4087. */
  4088. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4089. /**
  4090. * Returns a vector pointing in the same direction as another.
  4091. *
  4092. * @function
  4093. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4094. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4095. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4096. * @returns {Node<vec2|vec3|vec4>}
  4097. */
  4098. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4099. /**
  4100. * Returns a random value for the given uv.
  4101. *
  4102. * @function
  4103. * @param {Node<vec2>} uv - The uv node.
  4104. * @returns {Node<float>}
  4105. */
  4106. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4107. const a = 12.9898, b = 78.233, c = 43758.5453;
  4108. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4109. return fract( sin( sn ).mul( c ) );
  4110. } );
  4111. /**
  4112. * Alias for `mix()` with a different parameter order.
  4113. *
  4114. * @function
  4115. * @param {Node | Number} t - The interpolation value.
  4116. * @param {Node | Number} e1 - The first parameter.
  4117. * @param {Node | Number} e2 - The second parameter.
  4118. * @returns {Node}
  4119. */
  4120. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4121. /**
  4122. * Alias for `smoothstep()` with a different parameter order.
  4123. *
  4124. * @function
  4125. * @param {Node | Number} x - The source value for interpolation.
  4126. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4127. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4128. * @returns {Node}
  4129. */
  4130. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4131. /**
  4132. * Returns the arc-tangent of the quotient of its parameters.
  4133. *
  4134. * @function
  4135. * @deprecated since r172. Use {@link atan} instead.
  4136. *
  4137. * @param {Node | Number} y - The y parameter.
  4138. * @param {Node | Number} x - The x parameter.
  4139. * @returns {Node}
  4140. */
  4141. const atan2 = ( y, x ) => { // @deprecated, r172
  4142. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4143. return atan( y, x );
  4144. };
  4145. // GLSL alias function
  4146. const faceforward = faceForward;
  4147. const inversesqrt = inverseSqrt;
  4148. // Method chaining
  4149. addMethodChaining( 'all', all );
  4150. addMethodChaining( 'any', any );
  4151. addMethodChaining( 'equals', equals );
  4152. addMethodChaining( 'radians', radians );
  4153. addMethodChaining( 'degrees', degrees );
  4154. addMethodChaining( 'exp', exp );
  4155. addMethodChaining( 'exp2', exp2 );
  4156. addMethodChaining( 'log', log );
  4157. addMethodChaining( 'log2', log2 );
  4158. addMethodChaining( 'sqrt', sqrt );
  4159. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4160. addMethodChaining( 'floor', floor );
  4161. addMethodChaining( 'ceil', ceil );
  4162. addMethodChaining( 'normalize', normalize );
  4163. addMethodChaining( 'fract', fract );
  4164. addMethodChaining( 'sin', sin );
  4165. addMethodChaining( 'cos', cos );
  4166. addMethodChaining( 'tan', tan );
  4167. addMethodChaining( 'asin', asin );
  4168. addMethodChaining( 'acos', acos );
  4169. addMethodChaining( 'atan', atan );
  4170. addMethodChaining( 'abs', abs );
  4171. addMethodChaining( 'sign', sign );
  4172. addMethodChaining( 'length', length );
  4173. addMethodChaining( 'lengthSq', lengthSq );
  4174. addMethodChaining( 'negate', negate );
  4175. addMethodChaining( 'oneMinus', oneMinus );
  4176. addMethodChaining( 'dFdx', dFdx );
  4177. addMethodChaining( 'dFdy', dFdy );
  4178. addMethodChaining( 'round', round );
  4179. addMethodChaining( 'reciprocal', reciprocal );
  4180. addMethodChaining( 'trunc', trunc );
  4181. addMethodChaining( 'fwidth', fwidth );
  4182. addMethodChaining( 'atan2', atan2 );
  4183. addMethodChaining( 'min', min$1 );
  4184. addMethodChaining( 'max', max$1 );
  4185. addMethodChaining( 'mod', mod );
  4186. addMethodChaining( 'step', step );
  4187. addMethodChaining( 'reflect', reflect );
  4188. addMethodChaining( 'distance', distance );
  4189. addMethodChaining( 'dot', dot );
  4190. addMethodChaining( 'cross', cross );
  4191. addMethodChaining( 'pow', pow );
  4192. addMethodChaining( 'pow2', pow2 );
  4193. addMethodChaining( 'pow3', pow3 );
  4194. addMethodChaining( 'pow4', pow4 );
  4195. addMethodChaining( 'transformDirection', transformDirection );
  4196. addMethodChaining( 'mix', mixElement );
  4197. addMethodChaining( 'clamp', clamp );
  4198. addMethodChaining( 'refract', refract );
  4199. addMethodChaining( 'smoothstep', smoothstepElement );
  4200. addMethodChaining( 'faceForward', faceForward );
  4201. addMethodChaining( 'difference', difference );
  4202. addMethodChaining( 'saturate', saturate );
  4203. addMethodChaining( 'cbrt', cbrt );
  4204. addMethodChaining( 'transpose', transpose );
  4205. addMethodChaining( 'rand', rand );
  4206. /** @module ConditionalNode **/
  4207. /**
  4208. * Represents a logical `if/else` statement. Can be used as an alternative
  4209. * to the `If()`/`Else()` syntax.
  4210. *
  4211. * The corresponding TSL `select()` looks like so:
  4212. * ```js
  4213. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4214. * ```
  4215. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4216. * determine the outcome of the entire statement.
  4217. *
  4218. * @augments Node
  4219. */
  4220. class ConditionalNode extends Node {
  4221. static get type() {
  4222. return 'ConditionalNode';
  4223. }
  4224. /**
  4225. * Constructs a new conditional node.
  4226. *
  4227. * @param {Node} condNode - The node that defines the condition.
  4228. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4229. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4230. */
  4231. constructor( condNode, ifNode, elseNode = null ) {
  4232. super();
  4233. /**
  4234. * The node that defines the condition.
  4235. *
  4236. * @type {Node}
  4237. */
  4238. this.condNode = condNode;
  4239. /**
  4240. * The node that is evaluate when the condition ends up `true`.
  4241. *
  4242. * @type {Node}
  4243. */
  4244. this.ifNode = ifNode;
  4245. /**
  4246. * The node that is evaluate when the condition ends up `false`.
  4247. *
  4248. * @type {Node?}
  4249. * @default null
  4250. */
  4251. this.elseNode = elseNode;
  4252. }
  4253. /**
  4254. * This method is overwritten since the node type is inferred from the if/else
  4255. * nodes.
  4256. *
  4257. * @param {NodeBuilder} builder - The current node builder.
  4258. * @return {String} The node type.
  4259. */
  4260. getNodeType( builder ) {
  4261. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4262. if ( ifNode === undefined ) {
  4263. // fallback setup
  4264. this.setup( builder );
  4265. return this.getNodeType( builder );
  4266. }
  4267. const ifType = ifNode.getNodeType( builder );
  4268. if ( elseNode !== null ) {
  4269. const elseType = elseNode.getNodeType( builder );
  4270. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4271. return elseType;
  4272. }
  4273. }
  4274. return ifType;
  4275. }
  4276. setup( builder ) {
  4277. const condNode = this.condNode.cache();
  4278. const ifNode = this.ifNode.cache();
  4279. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4280. //
  4281. const currentNodeBlock = builder.context.nodeBlock;
  4282. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4283. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4284. //
  4285. const properties = builder.getNodeProperties( this );
  4286. properties.condNode = condNode;
  4287. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4288. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4289. }
  4290. generate( builder, output ) {
  4291. const type = this.getNodeType( builder );
  4292. const nodeData = builder.getDataFromNode( this );
  4293. if ( nodeData.nodeProperty !== undefined ) {
  4294. return nodeData.nodeProperty;
  4295. }
  4296. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4297. const needsOutput = output !== 'void';
  4298. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4299. nodeData.nodeProperty = nodeProperty;
  4300. const nodeSnippet = condNode.build( builder, 'bool' );
  4301. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4302. let ifSnippet = ifNode.build( builder, type );
  4303. if ( ifSnippet ) {
  4304. if ( needsOutput ) {
  4305. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4306. } else {
  4307. ifSnippet = 'return ' + ifSnippet + ';';
  4308. }
  4309. }
  4310. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4311. if ( elseNode !== null ) {
  4312. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4313. let elseSnippet = elseNode.build( builder, type );
  4314. if ( elseSnippet ) {
  4315. if ( needsOutput ) {
  4316. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4317. } else {
  4318. elseSnippet = 'return ' + elseSnippet + ';';
  4319. }
  4320. }
  4321. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4322. } else {
  4323. builder.addFlowCode( '\n\n' );
  4324. }
  4325. return builder.format( nodeProperty, type, output );
  4326. }
  4327. }
  4328. /**
  4329. * TSL function for creating a conditional node.
  4330. *
  4331. * @function
  4332. * @param {Node} condNode - The node that defines the condition.
  4333. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4334. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4335. * @returns {ConditionalNode}
  4336. */
  4337. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4338. addMethodChaining( 'select', select );
  4339. // Deprecated
  4340. /**
  4341. * @function
  4342. * @deprecated since r168. Use {@link select} instead.
  4343. *
  4344. * @param {...any} params
  4345. * @returns {ConditionalNode}
  4346. */
  4347. const cond = ( ...params ) => { // @deprecated, r168
  4348. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4349. return select( ...params );
  4350. };
  4351. addMethodChaining( 'cond', cond );
  4352. /** @module ContextNode **/
  4353. /**
  4354. * This node can be used as a context management component for another node.
  4355. * {@link NodeBuilder} performs its node building process in a specific context and
  4356. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4357. *
  4358. * ```js
  4359. *node.context( { getUV: () => customCoord } );
  4360. *```
  4361. * @augments Node
  4362. */
  4363. class ContextNode extends Node {
  4364. static get type() {
  4365. return 'ContextNode';
  4366. }
  4367. /**
  4368. * Constructs a new context node.
  4369. *
  4370. * @param {Node} node - The node whose context should be modified.
  4371. * @param {Object} [value={}] - The modified context data.
  4372. */
  4373. constructor( node, value = {} ) {
  4374. super();
  4375. /**
  4376. * This flag can be used for type testing.
  4377. *
  4378. * @type {Boolean}
  4379. * @readonly
  4380. * @default true
  4381. */
  4382. this.isContextNode = true;
  4383. /**
  4384. * The node whose context should be modified.
  4385. *
  4386. * @type {Node}
  4387. */
  4388. this.node = node;
  4389. /**
  4390. * The modified context data.
  4391. *
  4392. * @type {Object}
  4393. * @default {}
  4394. */
  4395. this.value = value;
  4396. }
  4397. /**
  4398. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4399. *
  4400. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4401. */
  4402. getScope() {
  4403. return this.node.getScope();
  4404. }
  4405. /**
  4406. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4407. *
  4408. * @param {NodeBuilder} builder - The current node builder.
  4409. * @return {String} The node type.
  4410. */
  4411. getNodeType( builder ) {
  4412. return this.node.getNodeType( builder );
  4413. }
  4414. analyze( builder ) {
  4415. this.node.build( builder );
  4416. }
  4417. setup( builder ) {
  4418. const previousContext = builder.getContext();
  4419. builder.setContext( { ...builder.context, ...this.value } );
  4420. const node = this.node.build( builder );
  4421. builder.setContext( previousContext );
  4422. return node;
  4423. }
  4424. generate( builder, output ) {
  4425. const previousContext = builder.getContext();
  4426. builder.setContext( { ...builder.context, ...this.value } );
  4427. const snippet = this.node.build( builder, output );
  4428. builder.setContext( previousContext );
  4429. return snippet;
  4430. }
  4431. }
  4432. /**
  4433. * TSL function for creating a context node.
  4434. *
  4435. * @function
  4436. * @param {Node} node - The node whose context should be modified.
  4437. * @param {Object} [value={}] - The modified context data.
  4438. * @returns {ContextNode}
  4439. */
  4440. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4441. /**
  4442. * TSL function for defining a label context value for a given node.
  4443. *
  4444. * @function
  4445. * @param {Node} node - The node whose context should be modified.
  4446. * @param {String} name - The name/label to set.
  4447. * @returns {ContextNode}
  4448. */
  4449. const label = ( node, name ) => context( node, { label: name } );
  4450. addMethodChaining( 'context', context );
  4451. addMethodChaining( 'label', label );
  4452. /** @module VarNode **/
  4453. /**
  4454. * Class for representing shader variables as nodes. Variables are created from
  4455. * existing nodes like the following:
  4456. *
  4457. * ```js
  4458. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4459. * ```
  4460. *
  4461. * @augments Node
  4462. */
  4463. class VarNode extends Node {
  4464. static get type() {
  4465. return 'VarNode';
  4466. }
  4467. /**
  4468. * Constructs a new variable node.
  4469. *
  4470. * @param {Node} node - The node for which a variable should be created.
  4471. * @param {String?} name - The name of the variable in the shader.
  4472. * @param {Boolean?} readOnly - The read-only flag.
  4473. */
  4474. constructor( node, name = null, readOnly = false ) {
  4475. super();
  4476. /**
  4477. * The node for which a variable should be created.
  4478. *
  4479. * @type {Node}
  4480. */
  4481. this.node = node;
  4482. /**
  4483. * The name of the variable in the shader. If no name is defined,
  4484. * the node system auto-generates one.
  4485. *
  4486. * @type {String?}
  4487. * @default null
  4488. */
  4489. this.name = name;
  4490. /**
  4491. * `VarNode` sets this property to `true` by default.
  4492. *
  4493. * @type {Boolean}
  4494. * @default true
  4495. */
  4496. this.global = true;
  4497. /**
  4498. * This flag can be used for type testing.
  4499. *
  4500. * @type {Boolean}
  4501. * @readonly
  4502. * @default true
  4503. */
  4504. this.isVarNode = true;
  4505. /**
  4506. *
  4507. * The read-only flag.
  4508. *
  4509. * @type {Boolean}
  4510. * @default false
  4511. */
  4512. this.readOnly = readOnly;
  4513. }
  4514. getHash( builder ) {
  4515. return this.name || super.getHash( builder );
  4516. }
  4517. getNodeType( builder ) {
  4518. return this.node.getNodeType( builder );
  4519. }
  4520. generate( builder ) {
  4521. const { node, name, readOnly } = this;
  4522. const { renderer } = builder;
  4523. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4524. let isDeterministic = false;
  4525. let shouldTreatAsReadOnly = false;
  4526. if ( readOnly ) {
  4527. isDeterministic = builder.isDeterministic( node );
  4528. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4529. }
  4530. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4531. const snippet = node.build( builder, vectorType );
  4532. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4533. const propertyName = builder.getPropertyName( nodeVar );
  4534. let declarationPrefix = propertyName;
  4535. if ( shouldTreatAsReadOnly ) {
  4536. const type = builder.getType( nodeVar.type );
  4537. if ( isWebGPUBackend ) {
  4538. declarationPrefix = isDeterministic
  4539. ? `const ${ propertyName }`
  4540. : `let ${ propertyName }`;
  4541. } else {
  4542. declarationPrefix = `const ${ type } ${ propertyName }`;
  4543. }
  4544. }
  4545. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4546. return propertyName;
  4547. }
  4548. }
  4549. /**
  4550. * TSL function for creating a var node.
  4551. *
  4552. * @function
  4553. * @param {Node} node - The node for which a variable should be created.
  4554. * @param {String?} name - The name of the variable in the shader.
  4555. * @returns {VarNode}
  4556. */
  4557. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4558. /**
  4559. * TSL function for creating a var node.
  4560. *
  4561. * @function
  4562. * @param {Node} node - The node for which a variable should be created.
  4563. * @param {String?} name - The name of the variable in the shader.
  4564. * @returns {VarNode}
  4565. */
  4566. const Var = ( node, name = null ) => createVar( node, name ).append();
  4567. /**
  4568. * TSL function for creating a const node.
  4569. *
  4570. * @function
  4571. * @param {Node} node - The node for which a constant should be created.
  4572. * @param {String?} name - The name of the constant in the shader.
  4573. * @returns {VarNode}
  4574. */
  4575. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4576. // Method chaining
  4577. addMethodChaining( 'toVar', Var );
  4578. addMethodChaining( 'toConst', Const );
  4579. // Deprecated
  4580. /**
  4581. * @function
  4582. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4583. *
  4584. * @param {Any} node
  4585. * @returns {VarNode}
  4586. */
  4587. const temp = ( node ) => { // @deprecated, r170
  4588. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4589. return createVar( node );
  4590. };
  4591. addMethodChaining( 'temp', temp );
  4592. /** @module VaryingNode **/
  4593. /**
  4594. * Class for representing shader varyings as nodes. Varyings are create from
  4595. * existing nodes like the following:
  4596. *
  4597. * ```js
  4598. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4599. * ```
  4600. *
  4601. * @augments Node
  4602. */
  4603. class VaryingNode extends Node {
  4604. static get type() {
  4605. return 'VaryingNode';
  4606. }
  4607. /**
  4608. * Constructs a new varying node.
  4609. *
  4610. * @param {Node} node - The node for which a varying should be created.
  4611. * @param {String?} name - The name of the varying in the shader.
  4612. */
  4613. constructor( node, name = null ) {
  4614. super();
  4615. /**
  4616. * The node for which a varying should be created.
  4617. *
  4618. * @type {Node}
  4619. */
  4620. this.node = node;
  4621. /**
  4622. * The name of the varying in the shader. If no name is defined,
  4623. * the node system auto-generates one.
  4624. *
  4625. * @type {String?}
  4626. * @default null
  4627. */
  4628. this.name = name;
  4629. /**
  4630. * This flag can be used for type testing.
  4631. *
  4632. * @type {Boolean}
  4633. * @readonly
  4634. * @default true
  4635. */
  4636. this.isVaryingNode = true;
  4637. }
  4638. /**
  4639. * The method is overwritten so it always returns `true`.
  4640. *
  4641. * @param {NodeBuilder} builder - The current node builder.
  4642. * @return {Boolean} Whether this node is global or not.
  4643. */
  4644. isGlobal( /*builder*/ ) {
  4645. return true;
  4646. }
  4647. getHash( builder ) {
  4648. return this.name || super.getHash( builder );
  4649. }
  4650. getNodeType( builder ) {
  4651. // VaryingNode is auto type
  4652. return this.node.getNodeType( builder );
  4653. }
  4654. /**
  4655. * This method performs the setup of a varying node with the current node builder.
  4656. *
  4657. * @param {NodeBuilder} builder - The current node builder.
  4658. * @return {NodeVarying} The node varying from the node builder.
  4659. */
  4660. setupVarying( builder ) {
  4661. const properties = builder.getNodeProperties( this );
  4662. let varying = properties.varying;
  4663. if ( varying === undefined ) {
  4664. const name = this.name;
  4665. const type = this.getNodeType( builder );
  4666. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4667. properties.node = this.node;
  4668. }
  4669. // this property can be used to check if the varying can be optimized for a variable
  4670. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4671. return varying;
  4672. }
  4673. setup( builder ) {
  4674. this.setupVarying( builder );
  4675. }
  4676. analyze( builder ) {
  4677. this.setupVarying( builder );
  4678. return this.node.analyze( builder );
  4679. }
  4680. generate( builder ) {
  4681. const properties = builder.getNodeProperties( this );
  4682. const varying = this.setupVarying( builder );
  4683. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4684. if ( properties.propertyName === undefined || needsReassign ) {
  4685. const type = this.getNodeType( builder );
  4686. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4687. // force node run in vertex stage
  4688. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4689. properties.propertyName = propertyName;
  4690. if ( needsReassign ) {
  4691. // once reassign varying in fragment stage
  4692. properties.reassignPosition = false;
  4693. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4694. properties.reassignPosition = true;
  4695. }
  4696. }
  4697. return builder.getPropertyName( varying );
  4698. }
  4699. }
  4700. /**
  4701. * TSL function for creating a varying node.
  4702. *
  4703. * @function
  4704. * @param {Node} node - The node for which a varying should be created.
  4705. * @param {String?} name - The name of the varying in the shader.
  4706. * @returns {VaryingNode}
  4707. */
  4708. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4709. /**
  4710. * Computes a node in the vertex stage.
  4711. *
  4712. * @function
  4713. * @param {Node} node - The node which should be executed in the vertex stage.
  4714. * @returns {VaryingNode}
  4715. */
  4716. const vertexStage = ( node ) => varying( node );
  4717. addMethodChaining( 'toVarying', varying );
  4718. addMethodChaining( 'toVertexStage', vertexStage );
  4719. // Deprecated
  4720. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  4721. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  4722. return varying( ...params );
  4723. } );
  4724. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  4725. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  4726. return varying( ...params );
  4727. } );
  4728. /** @module ColorSpaceFunctions **/
  4729. /**
  4730. * Converts the given color value from sRGB to linear-sRGB color space.
  4731. *
  4732. * @method
  4733. * @param {Node<vec3>} color - The sRGB color.
  4734. * @return {Node<vec3>} The linear-sRGB color.
  4735. */
  4736. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4737. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4738. const b = color.mul( 0.0773993808 );
  4739. const factor = color.lessThanEqual( 0.04045 );
  4740. const rgbResult = mix( a, b, factor );
  4741. return rgbResult;
  4742. } ).setLayout( {
  4743. name: 'sRGBTransferEOTF',
  4744. type: 'vec3',
  4745. inputs: [
  4746. { name: 'color', type: 'vec3' }
  4747. ]
  4748. } );
  4749. /**
  4750. * Converts the given color value from linear-sRGB to sRGB color space.
  4751. *
  4752. * @method
  4753. * @param {Node<vec3>} color - The linear-sRGB color.
  4754. * @return {Node<vec3>} The sRGB color.
  4755. */
  4756. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4757. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4758. const b = color.mul( 12.92 );
  4759. const factor = color.lessThanEqual( 0.0031308 );
  4760. const rgbResult = mix( a, b, factor );
  4761. return rgbResult;
  4762. } ).setLayout( {
  4763. name: 'sRGBTransferOETF',
  4764. type: 'vec3',
  4765. inputs: [
  4766. { name: 'color', type: 'vec3' }
  4767. ]
  4768. } );
  4769. /** @module ColorSpaceNode **/
  4770. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4771. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4772. /**
  4773. * This node represents a color space conversion. Meaning it converts
  4774. * a color value from a source to a target color space.
  4775. *
  4776. * @augments TempNode
  4777. */
  4778. class ColorSpaceNode extends TempNode {
  4779. static get type() {
  4780. return 'ColorSpaceNode';
  4781. }
  4782. /**
  4783. * Constructs a new color space node.
  4784. *
  4785. * @param {Node} colorNode - Represents the color to convert.
  4786. * @param {String} source - The source color space.
  4787. * @param {String} target - The target color space.
  4788. */
  4789. constructor( colorNode, source, target ) {
  4790. super( 'vec4' );
  4791. /**
  4792. * Represents the color to convert.
  4793. *
  4794. * @type {Node}
  4795. */
  4796. this.colorNode = colorNode;
  4797. /**
  4798. * The source color space.
  4799. *
  4800. * @type {String}
  4801. */
  4802. this.source = source;
  4803. /**
  4804. * The target color space.
  4805. *
  4806. * @type {String}
  4807. */
  4808. this.target = target;
  4809. }
  4810. /**
  4811. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4812. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4813. * color management and renderer.
  4814. *
  4815. * @param {NodeBuilder} builder - The current node builder.
  4816. * @param {String} colorSpace - The color space to resolve.
  4817. * @return {String} The resolved color space.
  4818. */
  4819. resolveColorSpace( builder, colorSpace ) {
  4820. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4821. return ColorManagement.workingColorSpace;
  4822. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4823. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4824. }
  4825. return colorSpace;
  4826. }
  4827. setup( builder ) {
  4828. const { colorNode } = this;
  4829. const source = this.resolveColorSpace( builder, this.source );
  4830. const target = this.resolveColorSpace( builder, this.target );
  4831. let outputNode = colorNode;
  4832. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4833. return outputNode;
  4834. }
  4835. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4836. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4837. }
  4838. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4839. outputNode = vec4(
  4840. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4841. outputNode.a
  4842. );
  4843. }
  4844. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4845. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4846. }
  4847. return outputNode;
  4848. }
  4849. }
  4850. /**
  4851. * TSL function for converting a given color node to the current output color space.
  4852. *
  4853. * @function
  4854. * @param {Node} node - Represents the node to convert.
  4855. * @returns {ColorSpaceNode}
  4856. */
  4857. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4858. /**
  4859. * TSL function for converting a given color node to the current working color space.
  4860. *
  4861. * @function
  4862. * @param {Node} node - Represents the node to convert.
  4863. * @returns {ColorSpaceNode}
  4864. */
  4865. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4866. /**
  4867. * TSL function for converting a given color node from the current working color space to the given color space.
  4868. *
  4869. * @function
  4870. * @param {Node} node - Represents the node to convert.
  4871. * @param {String} colorSpace - The target color space.
  4872. * @returns {ColorSpaceNode}
  4873. */
  4874. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4875. /**
  4876. * TSL function for converting a given color node from the given color space to the current working color space.
  4877. *
  4878. * @function
  4879. * @param {Node} node - Represents the node to convert.
  4880. * @param {String} colorSpace - The source color space.
  4881. * @returns {ColorSpaceNode}
  4882. */
  4883. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4884. /**
  4885. * TSL function for converting a given color node from one color space to another one.
  4886. *
  4887. * @function
  4888. * @param {Node} node - Represents the node to convert.
  4889. * @param {String} sourceColorSpace - The source color space.
  4890. * @param {String} targetColorSpace - The target color space.
  4891. * @returns {ColorSpaceNode}
  4892. */
  4893. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4894. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4895. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4896. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4897. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4898. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4899. /** @module ReferenceBaseNode **/
  4900. /**
  4901. * This class is only relevant if the referenced property is array-like.
  4902. * In this case, `ReferenceElementNode` allows to refer to a specific
  4903. * element inside the data structure via an index.
  4904. *
  4905. * @augments ArrayElementNode
  4906. */
  4907. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4908. static get type() {
  4909. return 'ReferenceElementNode';
  4910. }
  4911. /**
  4912. * Constructs a new reference element node.
  4913. *
  4914. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  4915. * @param {Node} indexNode - The index node that defines the element access.
  4916. */
  4917. constructor( referenceNode, indexNode ) {
  4918. super( referenceNode, indexNode );
  4919. /**
  4920. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4921. * property references to the current node.
  4922. *
  4923. * @type {ReferenceBaseNode?}
  4924. * @default null
  4925. */
  4926. this.referenceNode = referenceNode;
  4927. /**
  4928. * This flag can be used for type testing.
  4929. *
  4930. * @type {Boolean}
  4931. * @readonly
  4932. * @default true
  4933. */
  4934. this.isReferenceElementNode = true;
  4935. }
  4936. /**
  4937. * This method is overwritten since the node type is inferred from
  4938. * the uniform type of the reference node.
  4939. *
  4940. * @return {String} The node type.
  4941. */
  4942. getNodeType() {
  4943. return this.referenceNode.uniformType;
  4944. }
  4945. generate( builder ) {
  4946. const snippet = super.generate( builder );
  4947. const arrayType = this.referenceNode.getNodeType();
  4948. const elementType = this.getNodeType();
  4949. return builder.format( snippet, arrayType, elementType );
  4950. }
  4951. };
  4952. /**
  4953. * Base class for nodes which establishes a reference to a property of another object.
  4954. * In this way, the value of the node is automatically linked to the value of
  4955. * referenced object. Reference nodes internally represent the linked value
  4956. * as a uniform.
  4957. *
  4958. * @augments Node
  4959. */
  4960. class ReferenceBaseNode extends Node {
  4961. static get type() {
  4962. return 'ReferenceBaseNode';
  4963. }
  4964. /**
  4965. * Constructs a new reference base node.
  4966. *
  4967. * @param {String} property - The name of the property the node refers to.
  4968. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4969. * @param {Object?} [object=null] - The object the property belongs to.
  4970. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4971. */
  4972. constructor( property, uniformType, object = null, count = null ) {
  4973. super();
  4974. /**
  4975. * The name of the property the node refers to.
  4976. *
  4977. * @type {String}
  4978. */
  4979. this.property = property;
  4980. /**
  4981. * The uniform type that should be used to represent the property value.
  4982. *
  4983. * @type {String}
  4984. */
  4985. this.uniformType = uniformType;
  4986. /**
  4987. * The object the property belongs to.
  4988. *
  4989. * @type {Object?}
  4990. * @default null
  4991. */
  4992. this.object = object;
  4993. /**
  4994. * When the linked property is an array, this parameter defines its length.
  4995. *
  4996. * @type {Number?}
  4997. * @default null
  4998. */
  4999. this.count = count;
  5000. /**
  5001. * The property name might have dots so nested properties can be referred.
  5002. * The hierarchy of the names is stored inside this array.
  5003. *
  5004. * @type {Array<String>}
  5005. */
  5006. this.properties = property.split( '.' );
  5007. /**
  5008. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5009. * since the final reference might be updated from calling code.
  5010. *
  5011. * @type {Object?}
  5012. * @default null
  5013. */
  5014. this.reference = object;
  5015. /**
  5016. * The uniform node that holds the value of the reference node.
  5017. *
  5018. * @type {UniformNode}
  5019. * @default null
  5020. */
  5021. this.node = null;
  5022. /**
  5023. * The uniform group of the internal uniform.
  5024. *
  5025. * @type {UniformGroupNode}
  5026. * @default null
  5027. */
  5028. this.group = null;
  5029. /**
  5030. * Overwritten since reference nodes are updated per object.
  5031. *
  5032. * @type {String}
  5033. * @default 'object'
  5034. */
  5035. this.updateType = NodeUpdateType.OBJECT;
  5036. }
  5037. /**
  5038. * Sets the uniform group for this reference node.
  5039. *
  5040. * @param {UniformGroupNode} group - The uniform group to set.
  5041. * @return {ReferenceBaseNode} A reference to this node.
  5042. */
  5043. setGroup( group ) {
  5044. this.group = group;
  5045. return this;
  5046. }
  5047. /**
  5048. * When the referred property is array-like, this method can be used
  5049. * to access elements via an index node.
  5050. *
  5051. * @param {IndexNode} indexNode - indexNode.
  5052. * @return {ReferenceElementNode} A reference to an element.
  5053. */
  5054. element( indexNode ) {
  5055. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5056. }
  5057. /**
  5058. * Sets the node type which automatically defines the internal
  5059. * uniform type.
  5060. *
  5061. * @param {String} uniformType - The type to set.
  5062. */
  5063. setNodeType( uniformType ) {
  5064. const node = uniform( null, uniformType ).getSelf();
  5065. if ( this.group !== null ) {
  5066. node.setGroup( this.group );
  5067. }
  5068. this.node = node;
  5069. }
  5070. /**
  5071. * This method is overwritten since the node type is inferred from
  5072. * the type of the reference node.
  5073. *
  5074. * @param {NodeBuilder} builder - The current node builder.
  5075. * @return {String} The node type.
  5076. */
  5077. getNodeType( builder ) {
  5078. if ( this.node === null ) {
  5079. this.updateReference( builder );
  5080. this.updateValue();
  5081. }
  5082. return this.node.getNodeType( builder );
  5083. }
  5084. /**
  5085. * Returns the property value from the given referred object.
  5086. *
  5087. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5088. * @return {Any} The value.
  5089. */
  5090. getValueFromReference( object = this.reference ) {
  5091. const { properties } = this;
  5092. let value = object[ properties[ 0 ] ];
  5093. for ( let i = 1; i < properties.length; i ++ ) {
  5094. value = value[ properties[ i ] ];
  5095. }
  5096. return value;
  5097. }
  5098. /**
  5099. * Allows to update the reference based on the given state. The state is only
  5100. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5101. *
  5102. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5103. * @return {Object} The updated reference.
  5104. */
  5105. updateReference( state ) {
  5106. this.reference = this.object !== null ? this.object : state.object;
  5107. return this.reference;
  5108. }
  5109. /**
  5110. * The output of the reference node is the internal uniform node.
  5111. *
  5112. * @return {UniformNode} The output node.
  5113. */
  5114. setup() {
  5115. this.updateValue();
  5116. return this.node;
  5117. }
  5118. /**
  5119. * Overwritten to to update the internal uniform value.
  5120. *
  5121. * @param {NodeFrame} frame - A reference to the current node frame.
  5122. */
  5123. update( /*frame*/ ) {
  5124. this.updateValue();
  5125. }
  5126. /**
  5127. * Retrieves the value from the referred object property and uses it
  5128. * to updated the internal uniform.
  5129. */
  5130. updateValue() {
  5131. if ( this.node === null ) this.setNodeType( this.uniformType );
  5132. const value = this.getValueFromReference();
  5133. if ( Array.isArray( value ) ) {
  5134. this.node.array = value;
  5135. } else {
  5136. this.node.value = value;
  5137. }
  5138. }
  5139. }
  5140. /**
  5141. * TSL function for creating a reference base node.
  5142. *
  5143. * @function
  5144. * @param {String} name - The name of the property the node refers to.
  5145. * @param {String} type - The uniform type that should be used to represent the property value.
  5146. * @param {Object} object - The object the property belongs to.
  5147. * @returns {ReferenceBaseNode}
  5148. */
  5149. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5150. /** @module RendererReferenceNode **/
  5151. /**
  5152. * This node is a special type of reference node which is intended
  5153. * for linking renderer properties with node values.
  5154. * ```js
  5155. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5156. * ```
  5157. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5158. * automatically be updated.
  5159. *
  5160. * @augments ReferenceBaseNode
  5161. */
  5162. class RendererReferenceNode extends ReferenceBaseNode {
  5163. static get type() {
  5164. return 'RendererReferenceNode';
  5165. }
  5166. /**
  5167. * Constructs a new renderer reference node.
  5168. *
  5169. * @param {String} property - The name of the property the node refers to.
  5170. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5171. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5172. * the node refers to the renderer of the current state.
  5173. */
  5174. constructor( property, inputType, renderer = null ) {
  5175. super( property, inputType, renderer );
  5176. /**
  5177. * The renderer the property belongs to. When no renderer is set,
  5178. * the node refers to the renderer of the current state.
  5179. *
  5180. * @type {Renderer?}
  5181. * @default null
  5182. */
  5183. this.renderer = renderer;
  5184. this.setGroup( renderGroup );
  5185. }
  5186. /**
  5187. * Updates the reference based on the given state. The state is only evaluated
  5188. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5189. *
  5190. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5191. * @return {Object} The updated reference.
  5192. */
  5193. updateReference( state ) {
  5194. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5195. return this.reference;
  5196. }
  5197. }
  5198. /**
  5199. * TSL function for creating a renderer reference node.
  5200. *
  5201. * @function
  5202. * @param {String} name - The name of the property the node refers to.
  5203. * @param {String} type - The uniform type that should be used to represent the property value.
  5204. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5205. * the node refers to the renderer of the current state.
  5206. * @returns {RendererReferenceNode}
  5207. */
  5208. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5209. /** @module ToneMappingNode **/
  5210. /**
  5211. * This node represents a tone mapping operation.
  5212. *
  5213. * @augments TempNode
  5214. */
  5215. class ToneMappingNode extends TempNode {
  5216. static get type() {
  5217. return 'ToneMappingNode';
  5218. }
  5219. /**
  5220. * Constructs a new tone mapping node.
  5221. *
  5222. * @param {Number} toneMapping - The tone mapping type.
  5223. * @param {Node} exposureNode - The tone mapping exposure.
  5224. * @param {Node} [colorNode=null] - The color node to process.
  5225. */
  5226. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5227. super( 'vec3' );
  5228. /**
  5229. * The tone mapping type.
  5230. *
  5231. * @type {Number}
  5232. */
  5233. this.toneMapping = toneMapping;
  5234. /**
  5235. * The tone mapping exposure.
  5236. *
  5237. * @type {Node}
  5238. * @default null
  5239. */
  5240. this.exposureNode = exposureNode;
  5241. /**
  5242. * Represents the color to process.
  5243. *
  5244. * @type {Node?}
  5245. * @default null
  5246. */
  5247. this.colorNode = colorNode;
  5248. }
  5249. /**
  5250. * Overwrites the default `customCacheKey()` implementation by including the tone
  5251. * mapping type into the cache key.
  5252. *
  5253. * @return {Number} The hash.
  5254. */
  5255. customCacheKey() {
  5256. return hash$1( this.toneMapping );
  5257. }
  5258. setup( builder ) {
  5259. const colorNode = this.colorNode || builder.context.color;
  5260. const toneMapping = this.toneMapping;
  5261. if ( toneMapping === NoToneMapping ) return colorNode;
  5262. let outputNode = null;
  5263. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5264. if ( toneMappingFn !== null ) {
  5265. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5266. } else {
  5267. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5268. outputNode = colorNode;
  5269. }
  5270. return outputNode;
  5271. }
  5272. }
  5273. /**
  5274. * TSL function for creating a tone mapping node.
  5275. *
  5276. * @function
  5277. * @param {Number} mapping - The tone mapping type.
  5278. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5279. * @param {Node<vec3> | Color} color - The color node to process.
  5280. * @returns {ToneMappingNode<vec3>}
  5281. */
  5282. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5283. /**
  5284. * TSL object that represents the global tone mapping exposure of the renderer.
  5285. *
  5286. * @type {RendererReferenceNode<vec3>}
  5287. */
  5288. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5289. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5290. /** @module BufferAttributeNode **/
  5291. /**
  5292. * In earlier `three.js` versions it was only possible to define attribute data
  5293. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5294. * on the node level.
  5295. * ```js
  5296. * const geometry = new THREE.PlaneGeometry();
  5297. * const positionAttribute = geometry.getAttribute( 'position' );
  5298. *
  5299. * const colors = [];
  5300. * for ( let i = 0; i < position.count; i ++ ) {
  5301. * colors.push( 1, 0, 0 );
  5302. * }
  5303. *
  5304. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5305. * ```
  5306. * This new approach is especially interesting when geometry data are generated via
  5307. * compute shaders. The below line converts a storage buffer into an attribute node.
  5308. * ```js
  5309. * material.positionNode = positionBuffer.toAttribute();
  5310. * ```
  5311. * @augments InputNode
  5312. */
  5313. class BufferAttributeNode extends InputNode {
  5314. static get type() {
  5315. return 'BufferAttributeNode';
  5316. }
  5317. /**
  5318. * Constructs a new buffer attribute node.
  5319. *
  5320. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5321. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5322. * @param {Number} [bufferStride=0] - The buffer stride.
  5323. * @param {Number} [bufferOffset=0] - The buffer offset.
  5324. */
  5325. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5326. super( value, bufferType );
  5327. /**
  5328. * This flag can be used for type testing.
  5329. *
  5330. * @type {Boolean}
  5331. * @readonly
  5332. * @default true
  5333. */
  5334. this.isBufferNode = true;
  5335. /**
  5336. * The buffer type (e.g. `'vec3'`).
  5337. *
  5338. * @type {String}
  5339. * @default null
  5340. */
  5341. this.bufferType = bufferType;
  5342. /**
  5343. * The buffer stride.
  5344. *
  5345. * @type {Number}
  5346. * @default 0
  5347. */
  5348. this.bufferStride = bufferStride;
  5349. /**
  5350. * The buffer offset.
  5351. *
  5352. * @type {Number}
  5353. * @default 0
  5354. */
  5355. this.bufferOffset = bufferOffset;
  5356. /**
  5357. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5358. * if you are planning to update the attribute data per frame.
  5359. *
  5360. * @type {Number}
  5361. * @default StaticDrawUsage
  5362. */
  5363. this.usage = StaticDrawUsage;
  5364. /**
  5365. * Whether the attribute is instanced or not.
  5366. *
  5367. * @type {Boolean}
  5368. * @default false
  5369. */
  5370. this.instanced = false;
  5371. /**
  5372. * A reference to the buffer attribute.
  5373. *
  5374. * @type {BufferAttribute?}
  5375. * @default null
  5376. */
  5377. this.attribute = null;
  5378. /**
  5379. * `BufferAttributeNode` sets this property to `true` by default.
  5380. *
  5381. * @type {Boolean}
  5382. * @default true
  5383. */
  5384. this.global = true;
  5385. if ( value && value.isBufferAttribute === true ) {
  5386. this.attribute = value;
  5387. this.usage = value.usage;
  5388. this.instanced = value.isInstancedBufferAttribute;
  5389. }
  5390. }
  5391. /**
  5392. * This method is overwritten since the attribute data might be shared
  5393. * and thus the hash should be shared as well.
  5394. *
  5395. * @param {NodeBuilder} builder - The current node builder.
  5396. * @return {String} The hash.
  5397. */
  5398. getHash( builder ) {
  5399. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5400. let bufferData = builder.globalCache.getData( this.value );
  5401. if ( bufferData === undefined ) {
  5402. bufferData = {
  5403. node: this
  5404. };
  5405. builder.globalCache.setData( this.value, bufferData );
  5406. }
  5407. return bufferData.node.uuid;
  5408. }
  5409. return this.uuid;
  5410. }
  5411. /**
  5412. * This method is overwritten since the node type is inferred from
  5413. * the buffer attribute.
  5414. *
  5415. * @param {NodeBuilder} builder - The current node builder.
  5416. * @return {String} The node type.
  5417. */
  5418. getNodeType( builder ) {
  5419. if ( this.bufferType === null ) {
  5420. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5421. }
  5422. return this.bufferType;
  5423. }
  5424. /**
  5425. * Depending on which value was passed to the node, `setup()` behaves
  5426. * differently. If no instance of `BufferAttribute` was passed, the method
  5427. * creates an internal attribute and configures it respectively.
  5428. *
  5429. * @param {NodeBuilder} builder - The current node builder.
  5430. */
  5431. setup( builder ) {
  5432. if ( this.attribute !== null ) return;
  5433. const type = this.getNodeType( builder );
  5434. const array = this.value;
  5435. const itemSize = builder.getTypeLength( type );
  5436. const stride = this.bufferStride || itemSize;
  5437. const offset = this.bufferOffset;
  5438. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5439. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5440. buffer.setUsage( this.usage );
  5441. this.attribute = bufferAttribute;
  5442. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5443. }
  5444. /**
  5445. * Generates the code snippet of the buffer attribute node.
  5446. *
  5447. * @param {NodeBuilder} builder - The current node builder.
  5448. * @return {String} The generated code snippet.
  5449. */
  5450. generate( builder ) {
  5451. const nodeType = this.getNodeType( builder );
  5452. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5453. const propertyName = builder.getPropertyName( nodeAttribute );
  5454. let output = null;
  5455. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5456. this.name = propertyName;
  5457. output = propertyName;
  5458. } else {
  5459. const nodeVarying = varying( this );
  5460. output = nodeVarying.build( builder, nodeType );
  5461. }
  5462. return output;
  5463. }
  5464. /**
  5465. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5466. *
  5467. * @param {NodeBuilder} builder - The current node builder.
  5468. * @return {String} The input type.
  5469. */
  5470. getInputType( /*builder*/ ) {
  5471. return 'bufferAttribute';
  5472. }
  5473. /**
  5474. * Sets the `usage` property to the given value.
  5475. *
  5476. * @param {Number} value - The usage to set.
  5477. * @return {BufferAttributeNode} A reference to this node.
  5478. */
  5479. setUsage( value ) {
  5480. this.usage = value;
  5481. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5482. this.attribute.usage = value;
  5483. }
  5484. return this;
  5485. }
  5486. /**
  5487. * Sets the `instanced` property to the given value.
  5488. *
  5489. * @param {Boolean} value - The value to set.
  5490. * @return {BufferAttributeNode} A reference to this node.
  5491. */
  5492. setInstanced( value ) {
  5493. this.instanced = value;
  5494. return this;
  5495. }
  5496. }
  5497. /**
  5498. * TSL function for creating a buffer attribute node.
  5499. *
  5500. * @function
  5501. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5502. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5503. * @param {Number} [stride=0] - The buffer stride.
  5504. * @param {Number} [offset=0] - The buffer offset.
  5505. * @returns {BufferAttributeNode}
  5506. */
  5507. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5508. /**
  5509. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5510. * Use this function if attribute data are updated per frame.
  5511. *
  5512. * @function
  5513. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5514. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5515. * @param {Number} [stride=0] - The buffer stride.
  5516. * @param {Number} [offset=0] - The buffer offset.
  5517. * @returns {BufferAttributeNode}
  5518. */
  5519. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5520. /**
  5521. * TSL function for creating a buffer attribute node but with enabled instancing
  5522. *
  5523. * @function
  5524. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5525. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5526. * @param {Number} [stride=0] - The buffer stride.
  5527. * @param {Number} [offset=0] - The buffer offset.
  5528. * @returns {BufferAttributeNode}
  5529. */
  5530. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5531. /**
  5532. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5533. *
  5534. * @function
  5535. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5536. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5537. * @param {Number} [stride=0] - The buffer stride.
  5538. * @param {Number} [offset=0] - The buffer offset.
  5539. * @returns {BufferAttributeNode}
  5540. */
  5541. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5542. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5543. /** @module ComputeNode **/
  5544. /**
  5545. * TODO
  5546. *
  5547. * @augments Node
  5548. */
  5549. class ComputeNode extends Node {
  5550. static get type() {
  5551. return 'ComputeNode';
  5552. }
  5553. /**
  5554. * Constructs a new compute node.
  5555. *
  5556. * @param {Node} computeNode - TODO
  5557. * @param {Number} count - TODO.
  5558. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5559. */
  5560. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5561. super( 'void' );
  5562. /**
  5563. * This flag can be used for type testing.
  5564. *
  5565. * @type {Boolean}
  5566. * @readonly
  5567. * @default true
  5568. */
  5569. this.isComputeNode = true;
  5570. /**
  5571. * TODO
  5572. *
  5573. * @type {Node}
  5574. */
  5575. this.computeNode = computeNode;
  5576. /**
  5577. * TODO
  5578. *
  5579. * @type {Number}
  5580. */
  5581. this.count = count;
  5582. /**
  5583. * TODO
  5584. *
  5585. * @type {Array<Number>}
  5586. * @default [64]
  5587. */
  5588. this.workgroupSize = workgroupSize;
  5589. /**
  5590. * TODO
  5591. *
  5592. * @type {Number}
  5593. */
  5594. this.dispatchCount = 0;
  5595. /**
  5596. * TODO
  5597. *
  5598. * @type {Number}
  5599. */
  5600. this.version = 1;
  5601. /**
  5602. * The name or label of the uniform.
  5603. *
  5604. * @type {String}
  5605. * @default ''
  5606. */
  5607. this.name = '';
  5608. /**
  5609. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5610. * is executed once per object by default.
  5611. *
  5612. * @type {String}
  5613. * @default 'object'
  5614. */
  5615. this.updateBeforeType = NodeUpdateType.OBJECT;
  5616. /**
  5617. * TODO
  5618. *
  5619. * @type {Function}
  5620. */
  5621. this.onInitFunction = null;
  5622. this.updateDispatchCount();
  5623. }
  5624. /**
  5625. * Executes the `dispose` event for this node.
  5626. */
  5627. dispose() {
  5628. this.dispatchEvent( { type: 'dispose' } );
  5629. }
  5630. /**
  5631. * Sets the {@link ComputeNode#name} property.
  5632. *
  5633. * @param {String} name - The name of the uniform.
  5634. * @return {ComputeNode} A reference to this node.
  5635. */
  5636. label( name ) {
  5637. this.name = name;
  5638. return this;
  5639. }
  5640. /**
  5641. * TODO
  5642. */
  5643. updateDispatchCount() {
  5644. const { count, workgroupSize } = this;
  5645. let size = workgroupSize[ 0 ];
  5646. for ( let i = 1; i < workgroupSize.length; i ++ )
  5647. size *= workgroupSize[ i ];
  5648. this.dispatchCount = Math.ceil( count / size );
  5649. }
  5650. /**
  5651. * TODO
  5652. *
  5653. * @param {Function} callback - TODO.
  5654. * @return {ComputeNode} A reference to this node.
  5655. */
  5656. onInit( callback ) {
  5657. this.onInitFunction = callback;
  5658. return this;
  5659. }
  5660. /**
  5661. * The method execute the compute for this node.
  5662. *
  5663. * @param {NodeFrame} frame - A reference to the current node frame.
  5664. */
  5665. updateBefore( { renderer } ) {
  5666. renderer.compute( this );
  5667. }
  5668. generate( builder ) {
  5669. const { shaderStage } = builder;
  5670. if ( shaderStage === 'compute' ) {
  5671. const snippet = this.computeNode.build( builder, 'void' );
  5672. if ( snippet !== '' ) {
  5673. builder.addLineFlowCode( snippet, this );
  5674. }
  5675. }
  5676. }
  5677. }
  5678. /**
  5679. * TSL function for creating a compute node.
  5680. *
  5681. * @function
  5682. * @param {Node} node - TODO
  5683. * @param {Number} count - TODO.
  5684. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5685. * @returns {AtomicFunctionNode}
  5686. */
  5687. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5688. addMethodChaining( 'compute', compute );
  5689. /** @module CacheNode **/
  5690. /**
  5691. * This node can be used as a cache management component for another node.
  5692. * Caching is in general used by default in {@link NodeBuilder} but this node
  5693. * allows the usage of a shared parent cache during the build process.
  5694. *
  5695. * @augments Node
  5696. */
  5697. class CacheNode extends Node {
  5698. static get type() {
  5699. return 'CacheNode';
  5700. }
  5701. /**
  5702. * Constructs a new cache node.
  5703. *
  5704. * @param {Node} node - The node that should be cached.
  5705. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5706. */
  5707. constructor( node, parent = true ) {
  5708. super();
  5709. /**
  5710. * The node that should be cached.
  5711. *
  5712. * @type {Node}
  5713. */
  5714. this.node = node;
  5715. /**
  5716. * Whether this node refers to a shared parent cache or not.
  5717. *
  5718. * @type {Boolean}
  5719. * @default true
  5720. */
  5721. this.parent = parent;
  5722. /**
  5723. * This flag can be used for type testing.
  5724. *
  5725. * @type {Boolean}
  5726. * @readonly
  5727. * @default true
  5728. */
  5729. this.isCacheNode = true;
  5730. }
  5731. getNodeType( builder ) {
  5732. const previousCache = builder.getCache();
  5733. const cache = builder.getCacheFromNode( this, this.parent );
  5734. builder.setCache( cache );
  5735. const nodeType = this.node.getNodeType( builder );
  5736. builder.setCache( previousCache );
  5737. return nodeType;
  5738. }
  5739. build( builder, ...params ) {
  5740. const previousCache = builder.getCache();
  5741. const cache = builder.getCacheFromNode( this, this.parent );
  5742. builder.setCache( cache );
  5743. const data = this.node.build( builder, ...params );
  5744. builder.setCache( previousCache );
  5745. return data;
  5746. }
  5747. }
  5748. /**
  5749. * TSL function for creating a cache node.
  5750. *
  5751. * @function
  5752. * @param {Node} node - The node that should be cached.
  5753. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5754. * @returns {CacheNode}
  5755. */
  5756. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5757. addMethodChaining( 'cache', cache );
  5758. /** @module BypassNode **/
  5759. /**
  5760. * The class generates the code of a given node but returns another node in the output.
  5761. * This can be used to call a method or node that does not return a value, i.e.
  5762. * type `void` on an input where returning a value is required. Example:
  5763. *
  5764. * ```js
  5765. * material.colorNode = myColor.bypass( runVoidFn() )
  5766. *```
  5767. *
  5768. * @augments Node
  5769. */
  5770. class BypassNode extends Node {
  5771. static get type() {
  5772. return 'BypassNode';
  5773. }
  5774. /**
  5775. * Constructs a new bypass node.
  5776. *
  5777. * @param {Node} outputNode - The output node.
  5778. * @param {Node} callNode - The call node.
  5779. */
  5780. constructor( outputNode, callNode ) {
  5781. super();
  5782. /**
  5783. * This flag can be used for type testing.
  5784. *
  5785. * @type {Boolean}
  5786. * @readonly
  5787. * @default true
  5788. */
  5789. this.isBypassNode = true;
  5790. /**
  5791. * The output node.
  5792. *
  5793. * @type {Node}
  5794. */
  5795. this.outputNode = outputNode;
  5796. /**
  5797. * The call node.
  5798. *
  5799. * @type {Node}
  5800. */
  5801. this.callNode = callNode;
  5802. }
  5803. getNodeType( builder ) {
  5804. return this.outputNode.getNodeType( builder );
  5805. }
  5806. generate( builder ) {
  5807. const snippet = this.callNode.build( builder, 'void' );
  5808. if ( snippet !== '' ) {
  5809. builder.addLineFlowCode( snippet, this );
  5810. }
  5811. return this.outputNode.build( builder );
  5812. }
  5813. }
  5814. /**
  5815. * TSL function for creating a bypass node.
  5816. *
  5817. * @function
  5818. * @param {Node} outputNode - The output node.
  5819. * @param {Node} callNode - The call node.
  5820. * @returns {BypassNode}
  5821. */
  5822. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5823. addMethodChaining( 'bypass', bypass );
  5824. /** @module RemapNode **/
  5825. /**
  5826. * This node allows to remap a node value from one range into another. E.g a value of
  5827. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5828. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5829. *
  5830. * @augments Node
  5831. */
  5832. class RemapNode extends Node {
  5833. static get type() {
  5834. return 'RemapNode';
  5835. }
  5836. /**
  5837. * Constructs a new remap node.
  5838. *
  5839. * @param {Node} node - The node that should be remapped.
  5840. * @param {Node} inLowNode - The source or current lower bound of the range.
  5841. * @param {Node} inHighNode - The source or current upper bound of the range.
  5842. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5843. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5844. */
  5845. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5846. super();
  5847. /**
  5848. * The node that should be remapped.
  5849. *
  5850. * @type {Node}
  5851. */
  5852. this.node = node;
  5853. /**
  5854. * The source or current lower bound of the range.
  5855. *
  5856. * @type {Node}
  5857. */
  5858. this.inLowNode = inLowNode;
  5859. /**
  5860. * The source or current upper bound of the range.
  5861. *
  5862. * @type {Node}
  5863. */
  5864. this.inHighNode = inHighNode;
  5865. /**
  5866. * The target lower bound of the range.
  5867. *
  5868. * @type {Node}
  5869. * @default float(0)
  5870. */
  5871. this.outLowNode = outLowNode;
  5872. /**
  5873. * The target upper bound of the range.
  5874. *
  5875. * @type {Node}
  5876. * @default float(1)
  5877. */
  5878. this.outHighNode = outHighNode;
  5879. /**
  5880. * Whether the node value should be clamped before
  5881. * remapping it to the target range.
  5882. *
  5883. * @type {Boolean}
  5884. * @default true
  5885. */
  5886. this.doClamp = true;
  5887. }
  5888. setup() {
  5889. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5890. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5891. if ( doClamp === true ) t = t.clamp();
  5892. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5893. }
  5894. }
  5895. /**
  5896. * TSL function for creating a remap node.
  5897. *
  5898. * @function
  5899. * @param {Node} node - The node that should be remapped.
  5900. * @param {Node} inLowNode - The source or current lower bound of the range.
  5901. * @param {Node} inHighNode - The source or current upper bound of the range.
  5902. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5903. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5904. * @returns {RemapNode}
  5905. */
  5906. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5907. /**
  5908. * TSL function for creating a remap node, but with enabled clamping.
  5909. *
  5910. * @function
  5911. * @param {Node} node - The node that should be remapped.
  5912. * @param {Node} inLowNode - The source or current lower bound of the range.
  5913. * @param {Node} inHighNode - The source or current upper bound of the range.
  5914. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5915. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5916. * @returns {RemapNode}
  5917. */
  5918. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5919. addMethodChaining( 'remap', remap );
  5920. addMethodChaining( 'remapClamp', remapClamp );
  5921. /** @module ExpressionNode **/
  5922. /**
  5923. * This class can be used to implement basic expressions in shader code.
  5924. * Basic examples for that are `return`, `continue` or `discard` statements.
  5925. *
  5926. * @augments Node
  5927. */
  5928. class ExpressionNode extends Node {
  5929. static get type() {
  5930. return 'ExpressionNode';
  5931. }
  5932. /**
  5933. * Constructs a new expression node.
  5934. *
  5935. * @param {String} [snippet=''] - The native code snippet.
  5936. * @param {String} [nodeType='void'] - The node type.
  5937. */
  5938. constructor( snippet = '', nodeType = 'void' ) {
  5939. super( nodeType );
  5940. /**
  5941. * The native code snippet.
  5942. *
  5943. * @type {String}
  5944. * @default ''
  5945. */
  5946. this.snippet = snippet;
  5947. }
  5948. generate( builder, output ) {
  5949. const type = this.getNodeType( builder );
  5950. const snippet = this.snippet;
  5951. if ( type === 'void' ) {
  5952. builder.addLineFlowCode( snippet, this );
  5953. } else {
  5954. return builder.format( `( ${ snippet } )`, type, output );
  5955. }
  5956. }
  5957. }
  5958. /**
  5959. * TSL function for creating an expression node.
  5960. *
  5961. * @function
  5962. * @param {String} [snippet=''] - The native code snippet.
  5963. * @param {String} [nodeType='void'] - The node type.
  5964. * @returns {ExpressionNode}
  5965. */
  5966. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5967. /** @module Discard **/
  5968. /**
  5969. * Represents a `discard` shader operation in TSL.
  5970. *
  5971. * @method
  5972. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5973. * @return {Node} The `discard` expression.
  5974. */
  5975. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5976. /**
  5977. * Represents a `return` shader operation in TSL.
  5978. *
  5979. * @method
  5980. * @return {ExpressionNode} The `return` expression.
  5981. */
  5982. const Return = () => expression( 'return' ).append();
  5983. addMethodChaining( 'discard', Discard );
  5984. /** @module RenderOutputNode **/
  5985. /**
  5986. * Normally, tone mapping and color conversion happens automatically
  5987. * before outputting pixel too the default (screen) framebuffer. In certain
  5988. * post processing setups this happens to late because certain effects
  5989. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5990. * to apply tone mapping and color space conversion at an arbitrary point
  5991. * in the effect chain.
  5992. *
  5993. * When applying tone mapping and color space conversion manually with this node,
  5994. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5995. *
  5996. * ```js
  5997. * const postProcessing = new PostProcessing( renderer );
  5998. * postProcessing.outputColorTransform = false;
  5999. *
  6000. * const scenePass = pass( scene, camera );
  6001. * const outputPass = renderOutput( scenePass );
  6002. *
  6003. * postProcessing.outputNode = outputPass;
  6004. * ```
  6005. *
  6006. * @augments TempNode
  6007. */
  6008. class RenderOutputNode extends TempNode {
  6009. static get type() {
  6010. return 'RenderOutputNode';
  6011. }
  6012. /**
  6013. * Constructs a new render output node.
  6014. *
  6015. * @param {Node} colorNode - The color node to process.
  6016. * @param {Number} toneMapping - The tone mapping type.
  6017. * @param {String} outputColorSpace - The output color space.
  6018. */
  6019. constructor( colorNode, toneMapping, outputColorSpace ) {
  6020. super( 'vec4' );
  6021. /**
  6022. * The color node to process.
  6023. *
  6024. * @type {Node}
  6025. */
  6026. this.colorNode = colorNode;
  6027. /**
  6028. * The tone mapping type.
  6029. *
  6030. * @type {Number?}
  6031. */
  6032. this.toneMapping = toneMapping;
  6033. /**
  6034. * The output color space.
  6035. *
  6036. * @type {String?}
  6037. */
  6038. this.outputColorSpace = outputColorSpace;
  6039. /**
  6040. * This flag can be used for type testing.
  6041. *
  6042. * @type {Boolean}
  6043. * @readonly
  6044. * @default true
  6045. */
  6046. this.isRenderOutputNode = true;
  6047. }
  6048. setup( { context } ) {
  6049. let outputNode = this.colorNode || context.color;
  6050. // tone mapping
  6051. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6052. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6053. if ( toneMapping !== NoToneMapping ) {
  6054. outputNode = outputNode.toneMapping( toneMapping );
  6055. }
  6056. // working to output color space
  6057. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6058. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6059. }
  6060. return outputNode;
  6061. }
  6062. }
  6063. /**
  6064. * TSL function for creating a posterize node.
  6065. *
  6066. * @function
  6067. * @param {Node} color - The color node to process.
  6068. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6069. * @param {String?} [outputColorSpace=null] - The output color space.
  6070. * @returns {RenderOutputNode}
  6071. */
  6072. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6073. addMethodChaining( 'renderOutput', renderOutput );
  6074. // Non-PURE exports list, side-effects are required here.
  6075. // TSL Base Syntax
  6076. function addNodeElement( name/*, nodeElement*/ ) {
  6077. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6078. }
  6079. /** @module AttributeNode **/
  6080. /**
  6081. * Base class for representing shader attributes as nodes.
  6082. *
  6083. * @augments Node
  6084. */
  6085. class AttributeNode extends Node {
  6086. static get type() {
  6087. return 'AttributeNode';
  6088. }
  6089. /**
  6090. * Constructs a new attribute node.
  6091. *
  6092. * @param {String} attributeName - The name of the attribute.
  6093. * @param {String?} nodeType - The node type.
  6094. */
  6095. constructor( attributeName, nodeType = null ) {
  6096. super( nodeType );
  6097. /**
  6098. * `AttributeNode` sets this property to `true` by default.
  6099. *
  6100. * @type {Boolean}
  6101. * @default true
  6102. */
  6103. this.global = true;
  6104. this._attributeName = attributeName;
  6105. }
  6106. getHash( builder ) {
  6107. return this.getAttributeName( builder );
  6108. }
  6109. getNodeType( builder ) {
  6110. let nodeType = this.nodeType;
  6111. if ( nodeType === null ) {
  6112. const attributeName = this.getAttributeName( builder );
  6113. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6114. const attribute = builder.geometry.getAttribute( attributeName );
  6115. nodeType = builder.getTypeFromAttribute( attribute );
  6116. } else {
  6117. nodeType = 'float';
  6118. }
  6119. }
  6120. return nodeType;
  6121. }
  6122. /**
  6123. * Sets the attribute name to the given value. The method can be
  6124. * overwritten in derived classes if the final name must be computed
  6125. * analytically.
  6126. *
  6127. * @param {String} attributeName - The name of the attribute.
  6128. * @return {AttributeNode} A reference to this node.
  6129. */
  6130. setAttributeName( attributeName ) {
  6131. this._attributeName = attributeName;
  6132. return this;
  6133. }
  6134. /**
  6135. * Returns the attribute name of this node. The method can be
  6136. * overwritten in derived classes if the final name must be computed
  6137. * analytically.
  6138. *
  6139. * @param {NodeBuilder} builder - The current node builder.
  6140. * @return {String} The attribute name.
  6141. */
  6142. getAttributeName( /*builder*/ ) {
  6143. return this._attributeName;
  6144. }
  6145. generate( builder ) {
  6146. const attributeName = this.getAttributeName( builder );
  6147. const nodeType = this.getNodeType( builder );
  6148. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6149. if ( geometryAttribute === true ) {
  6150. const attribute = builder.geometry.getAttribute( attributeName );
  6151. const attributeType = builder.getTypeFromAttribute( attribute );
  6152. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6153. if ( builder.shaderStage === 'vertex' ) {
  6154. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6155. } else {
  6156. const nodeVarying = varying( this );
  6157. return nodeVarying.build( builder, nodeType );
  6158. }
  6159. } else {
  6160. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6161. return builder.generateConst( nodeType );
  6162. }
  6163. }
  6164. serialize( data ) {
  6165. super.serialize( data );
  6166. data.global = this.global;
  6167. data._attributeName = this._attributeName;
  6168. }
  6169. deserialize( data ) {
  6170. super.deserialize( data );
  6171. this.global = data.global;
  6172. this._attributeName = data._attributeName;
  6173. }
  6174. }
  6175. /**
  6176. * TSL function for creating an attribute node.
  6177. *
  6178. * @function
  6179. * @param {String} name - The name of the attribute.
  6180. * @param {String?} nodeType - The node type.
  6181. * @returns {AttributeNode}
  6182. */
  6183. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6184. /** @module UV **/
  6185. /**
  6186. * TSL function for creating an uv attribute node with the given index.
  6187. *
  6188. * @function
  6189. * @param {Number} [index=0] - The uv index.
  6190. * @return {AttributeNode<vec2>} The uv attribute node.
  6191. */
  6192. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6193. /** @module TextureSizeNode **/
  6194. /**
  6195. * A node that represents the dimensions of a texture. The texture size is
  6196. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6197. * or `textureSize()`.
  6198. *
  6199. * @augments Node
  6200. */
  6201. class TextureSizeNode extends Node {
  6202. static get type() {
  6203. return 'TextureSizeNode';
  6204. }
  6205. /**
  6206. * Constructs a new texture size node.
  6207. *
  6208. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6209. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6210. */
  6211. constructor( textureNode, levelNode = null ) {
  6212. super( 'uvec2' );
  6213. /**
  6214. * This flag can be used for type testing.
  6215. *
  6216. * @type {Boolean}
  6217. * @readonly
  6218. * @default true
  6219. */
  6220. this.isTextureSizeNode = true;
  6221. /**
  6222. * A texture node which size should be retrieved.
  6223. *
  6224. * @type {TextureNode}
  6225. */
  6226. this.textureNode = textureNode;
  6227. /**
  6228. * A level node which defines the requested mip.
  6229. *
  6230. * @type {Node<int>}
  6231. * @default null
  6232. */
  6233. this.levelNode = levelNode;
  6234. }
  6235. generate( builder, output ) {
  6236. const textureProperty = this.textureNode.build( builder, 'property' );
  6237. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6238. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6239. }
  6240. }
  6241. /**
  6242. * TSL function for creating a texture size node.
  6243. *
  6244. * @function
  6245. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6246. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6247. * @returns {TextureSizeNode}
  6248. */
  6249. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6250. /** @module MatcapUVNode **/
  6251. /**
  6252. * A special type of uniform node that computes the
  6253. * maximum mipmap level for a given texture node.
  6254. *
  6255. * ```js
  6256. * const level = maxMipLevel( textureNode );
  6257. * ```
  6258. *
  6259. * @augments module:UniformNode~UniformNode
  6260. */
  6261. class MaxMipLevelNode extends UniformNode {
  6262. static get type() {
  6263. return 'MaxMipLevelNode';
  6264. }
  6265. /**
  6266. * Constructs a new max mip level node.
  6267. *
  6268. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6269. */
  6270. constructor( textureNode ) {
  6271. super( 0 );
  6272. /**
  6273. * The texture node to compute the max mip level for.
  6274. *
  6275. * @private
  6276. * @type {TextureNode}
  6277. */
  6278. this._textureNode = textureNode;
  6279. /**
  6280. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6281. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6282. *
  6283. * @type {String}
  6284. * @default 'frame'
  6285. */
  6286. this.updateType = NodeUpdateType.FRAME;
  6287. }
  6288. /**
  6289. * The texture node to compute the max mip level for.
  6290. *
  6291. * @readonly
  6292. * @type {TextureNode}
  6293. */
  6294. get textureNode() {
  6295. return this._textureNode;
  6296. }
  6297. /**
  6298. * The texture.
  6299. *
  6300. * @readonly
  6301. * @type {Texture}
  6302. */
  6303. get texture() {
  6304. return this._textureNode.value;
  6305. }
  6306. update() {
  6307. const texture = this.texture;
  6308. const images = texture.images;
  6309. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6310. if ( image && image.width !== undefined ) {
  6311. const { width, height } = image;
  6312. this.value = Math.log2( Math.max( width, height ) );
  6313. }
  6314. }
  6315. }
  6316. /**
  6317. * TSL function for creating a max mip level node.
  6318. *
  6319. * @function
  6320. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6321. * @returns {MaxMipLevelNode}
  6322. */
  6323. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6324. /** @module TextureNode **/
  6325. /**
  6326. * This type of uniform node represents a 2D texture.
  6327. *
  6328. * @augments module:UniformNode~UniformNode
  6329. */
  6330. class TextureNode extends UniformNode {
  6331. static get type() {
  6332. return 'TextureNode';
  6333. }
  6334. /**
  6335. * Constructs a new texture node.
  6336. *
  6337. * @param {Texture} value - The texture.
  6338. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6339. * @param {Node<int>?} [levelNode=null] - The level node.
  6340. * @param {Node<float>?} [biasNode=null] - The bias node.
  6341. */
  6342. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6343. super( value );
  6344. /**
  6345. * This flag can be used for type testing.
  6346. *
  6347. * @type {Boolean}
  6348. * @readonly
  6349. * @default true
  6350. */
  6351. this.isTextureNode = true;
  6352. /**
  6353. * Represents the texture coordinates.
  6354. *
  6355. * @type {Node<vec2|vec3>?}
  6356. * @default null
  6357. */
  6358. this.uvNode = uvNode;
  6359. /**
  6360. * Represents the mip level that should be selected.
  6361. *
  6362. * @type {Node<int>?}
  6363. * @default null
  6364. */
  6365. this.levelNode = levelNode;
  6366. /**
  6367. * Represents the bias to be applied during level-of-detail computation.
  6368. *
  6369. * @type {Node<float>?}
  6370. * @default null
  6371. */
  6372. this.biasNode = biasNode;
  6373. /**
  6374. * Represents a reference value a texture sample is compared to.
  6375. *
  6376. * @type {Node<float>?}
  6377. * @default null
  6378. */
  6379. this.compareNode = null;
  6380. /**
  6381. * When using texture arrays, the depth node defines the layer to select.
  6382. *
  6383. * @type {Node<int>?}
  6384. * @default null
  6385. */
  6386. this.depthNode = null;
  6387. /**
  6388. * When defined, a texture is sampled using explicit gradients.
  6389. *
  6390. * @type {Array<Node<vec2>>?}
  6391. * @default null
  6392. */
  6393. this.gradNode = null;
  6394. /**
  6395. * Whether texture values should be sampled or fetched.
  6396. *
  6397. * @type {Boolean}
  6398. * @default true
  6399. */
  6400. this.sampler = true;
  6401. /**
  6402. * Whether the uv transformation matrix should be
  6403. * automatically updated or not. Use `setUpdateMatrix()`
  6404. * if you want to change the value of the property.
  6405. *
  6406. * @type {Boolean}
  6407. * @default false
  6408. */
  6409. this.updateMatrix = false;
  6410. /**
  6411. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6412. * sets the value to `frame` when the uv transformation matrix should
  6413. * automatically be updated.
  6414. *
  6415. * @type {String}
  6416. * @default 'none'
  6417. */
  6418. this.updateType = NodeUpdateType.NONE;
  6419. /**
  6420. * The reference node.
  6421. *
  6422. * @type {Node?}
  6423. * @default null
  6424. */
  6425. this.referenceNode = null;
  6426. /**
  6427. * The texture value is stored in a private property.
  6428. *
  6429. * @private
  6430. * @type {Texture}
  6431. */
  6432. this._value = value;
  6433. /**
  6434. * The uniform node that represents the uv transformation matrix.
  6435. *
  6436. * @private
  6437. * @type {UniformNode<mat3>?}
  6438. */
  6439. this._matrixUniform = null;
  6440. this.setUpdateMatrix( uvNode === null );
  6441. }
  6442. set value( value ) {
  6443. if ( this.referenceNode ) {
  6444. this.referenceNode.value = value;
  6445. } else {
  6446. this._value = value;
  6447. }
  6448. }
  6449. /**
  6450. * The texture value.
  6451. *
  6452. * @type {Texture}
  6453. */
  6454. get value() {
  6455. return this.referenceNode ? this.referenceNode.value : this._value;
  6456. }
  6457. /**
  6458. * Overwritten since the uniform hash is defined by the texture's UUID.
  6459. *
  6460. * @param {NodeBuilder} builder - The current node builder.
  6461. * @return {String} The uniform hash.
  6462. */
  6463. getUniformHash( /*builder*/ ) {
  6464. return this.value.uuid;
  6465. }
  6466. /**
  6467. * Overwritten since the node type is inferred from the texture type.
  6468. *
  6469. * @param {NodeBuilder} builder - The current node builder.
  6470. * @return {String} The node type.
  6471. */
  6472. getNodeType( /*builder*/ ) {
  6473. if ( this.value.isDepthTexture === true ) return 'float';
  6474. if ( this.value.type === UnsignedIntType ) {
  6475. return 'uvec4';
  6476. } else if ( this.value.type === IntType ) {
  6477. return 'ivec4';
  6478. }
  6479. return 'vec4';
  6480. }
  6481. /**
  6482. * Overwrites the default implementation to return a fixed value `'texture'`.
  6483. *
  6484. * @param {NodeBuilder} builder - The current node builder.
  6485. * @return {String} The input type.
  6486. */
  6487. getInputType( /*builder*/ ) {
  6488. return 'texture';
  6489. }
  6490. /**
  6491. * Returns a default uvs based on the current texture's channel.
  6492. *
  6493. * @return {AttributeNode<vec2>} The default uvs.
  6494. */
  6495. getDefaultUV() {
  6496. return uv( this.value.channel );
  6497. }
  6498. /**
  6499. * Overwritten to always return the texture reference of the node.
  6500. *
  6501. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6502. * @return {Texture} The texture reference.
  6503. */
  6504. updateReference( /*state*/ ) {
  6505. return this.value;
  6506. }
  6507. /**
  6508. * Transforms the given uv node with the texture transformation matrix.
  6509. *
  6510. * @param {Node} uvNode - The uv node to transform.
  6511. * @return {Node} The transformed uv node.
  6512. */
  6513. getTransformedUV( uvNode ) {
  6514. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6515. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6516. }
  6517. /**
  6518. * Defines whether the uv transformation matrix should automatically be updated or not.
  6519. *
  6520. * @param {Boolean} value - The update toggle.
  6521. * @return {TextureNode} A reference to this node.
  6522. */
  6523. setUpdateMatrix( value ) {
  6524. this.updateMatrix = value;
  6525. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6526. return this;
  6527. }
  6528. /**
  6529. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6530. * to modify the uv node for correct sampling.
  6531. *
  6532. * @param {NodeBuilder} builder - The current node builder.
  6533. * @param {Node} uvNode - The uv node to setup.
  6534. * @return {Node} The updated uv node.
  6535. */
  6536. setupUV( builder, uvNode ) {
  6537. const texture = this.value;
  6538. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6539. if ( this.sampler ) {
  6540. uvNode = uvNode.flipY();
  6541. } else {
  6542. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6543. }
  6544. }
  6545. return uvNode;
  6546. }
  6547. /**
  6548. * Setups texture node by preparing the internal nodes for code generation.
  6549. *
  6550. * @param {NodeBuilder} builder - The current node builder.
  6551. */
  6552. setup( builder ) {
  6553. const properties = builder.getNodeProperties( this );
  6554. properties.referenceNode = this.referenceNode;
  6555. //
  6556. const texture = this.value;
  6557. if ( ! texture || texture.isTexture !== true ) {
  6558. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6559. }
  6560. //
  6561. let uvNode = this.uvNode;
  6562. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6563. uvNode = builder.context.getUV( this );
  6564. }
  6565. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6566. if ( this.updateMatrix === true ) {
  6567. uvNode = this.getTransformedUV( uvNode );
  6568. }
  6569. uvNode = this.setupUV( builder, uvNode );
  6570. //
  6571. let levelNode = this.levelNode;
  6572. if ( levelNode === null && builder.context.getTextureLevel ) {
  6573. levelNode = builder.context.getTextureLevel( this );
  6574. }
  6575. //
  6576. properties.uvNode = uvNode;
  6577. properties.levelNode = levelNode;
  6578. properties.biasNode = this.biasNode;
  6579. properties.compareNode = this.compareNode;
  6580. properties.gradNode = this.gradNode;
  6581. properties.depthNode = this.depthNode;
  6582. }
  6583. /**
  6584. * Generates the uv code snippet.
  6585. *
  6586. * @param {NodeBuilder} builder - The current node builder.
  6587. * @param {Node} uvNode - The uv node to generate code for.
  6588. * @return {String} The generated code snippet.
  6589. */
  6590. generateUV( builder, uvNode ) {
  6591. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6592. }
  6593. /**
  6594. * Generates the snippet for the texture sampling.
  6595. *
  6596. * @param {NodeBuilder} builder - The current node builder.
  6597. * @param {String} textureProperty - The texture property.
  6598. * @param {String} uvSnippet - The uv snippet.
  6599. * @param {String?} levelSnippet - The level snippet.
  6600. * @param {String?} biasSnippet - The bias snippet.
  6601. * @param {String?} depthSnippet - The depth snippet.
  6602. * @param {String?} compareSnippet - The compare snippet.
  6603. * @param {Array<String>?} gradSnippet - The grad snippet.
  6604. * @return {String} The generated code snippet.
  6605. */
  6606. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6607. const texture = this.value;
  6608. let snippet;
  6609. if ( levelSnippet ) {
  6610. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6611. } else if ( biasSnippet ) {
  6612. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6613. } else if ( gradSnippet ) {
  6614. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6615. } else if ( compareSnippet ) {
  6616. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6617. } else if ( this.sampler === false ) {
  6618. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6619. } else {
  6620. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6621. }
  6622. return snippet;
  6623. }
  6624. /**
  6625. * Generates the code snippet of the texture node.
  6626. *
  6627. * @param {NodeBuilder} builder - The current node builder.
  6628. * @param {String} output - The current output.
  6629. * @return {String} The generated code snippet.
  6630. */
  6631. generate( builder, output ) {
  6632. const texture = this.value;
  6633. const properties = builder.getNodeProperties( this );
  6634. const textureProperty = super.generate( builder, 'property' );
  6635. if ( output === 'sampler' ) {
  6636. return textureProperty + '_sampler';
  6637. } else if ( builder.isReference( output ) ) {
  6638. return textureProperty;
  6639. } else {
  6640. const nodeData = builder.getDataFromNode( this );
  6641. let propertyName = nodeData.propertyName;
  6642. if ( propertyName === undefined ) {
  6643. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6644. const uvSnippet = this.generateUV( builder, uvNode );
  6645. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6646. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6647. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6648. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6649. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6650. const nodeVar = builder.getVarFromNode( this );
  6651. propertyName = builder.getPropertyName( nodeVar );
  6652. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6653. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6654. nodeData.snippet = snippet;
  6655. nodeData.propertyName = propertyName;
  6656. }
  6657. let snippet = propertyName;
  6658. const nodeType = this.getNodeType( builder );
  6659. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6660. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6661. }
  6662. return builder.format( snippet, nodeType, output );
  6663. }
  6664. }
  6665. /**
  6666. * Sets the sampler value.
  6667. *
  6668. * @param {Boolean} value - The sampler value to set.
  6669. * @return {TextureNode} A reference to this texture node.
  6670. */
  6671. setSampler( value ) {
  6672. this.sampler = value;
  6673. return this;
  6674. }
  6675. /**
  6676. * Returns the sampler value.
  6677. *
  6678. * @return {Boolean} The sampler value.
  6679. */
  6680. getSampler() {
  6681. return this.sampler;
  6682. }
  6683. // @TODO: Move to TSL
  6684. /**
  6685. * @function
  6686. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6687. *
  6688. * @param {Node} uvNode - The uv node.
  6689. * @return {TextureNode} A texture node representing the texture sample.
  6690. */
  6691. uv( uvNode ) { // @deprecated, r172
  6692. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6693. return this.sample( uvNode );
  6694. }
  6695. /**
  6696. * Samples the texture with the given uv node.
  6697. *
  6698. * @param {Node} uvNode - The uv node.
  6699. * @return {TextureNode} A texture node representing the texture sample.
  6700. */
  6701. sample( uvNode ) {
  6702. const textureNode = this.clone();
  6703. textureNode.uvNode = nodeObject( uvNode );
  6704. textureNode.referenceNode = this.getSelf();
  6705. return nodeObject( textureNode );
  6706. }
  6707. /**
  6708. * Samples a blurred version of the texture by defining an internal bias.
  6709. *
  6710. * @param {Node<float>} amountNode - How blurred the texture should be.
  6711. * @return {TextureNode} A texture node representing the texture sample.
  6712. */
  6713. blur( amountNode ) {
  6714. const textureNode = this.clone();
  6715. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6716. textureNode.referenceNode = this.getSelf();
  6717. return nodeObject( textureNode );
  6718. }
  6719. /**
  6720. * Samples a specific mip of the texture.
  6721. *
  6722. * @param {Node<int>} levelNode - The mip level to sample.
  6723. * @return {TextureNode} A texture node representing the texture sample.
  6724. */
  6725. level( levelNode ) {
  6726. const textureNode = this.clone();
  6727. textureNode.levelNode = nodeObject( levelNode );
  6728. textureNode.referenceNode = this.getSelf();
  6729. return nodeObject( textureNode );
  6730. }
  6731. /**
  6732. * Returns the texture size of the requested level.
  6733. *
  6734. * @param {Node<int>} levelNode - The level to compute the size for.
  6735. * @return {TextureSizeNode} The texture size.
  6736. */
  6737. size( levelNode ) {
  6738. return textureSize( this, levelNode );
  6739. }
  6740. /**
  6741. * Samples the texture with the given bias.
  6742. *
  6743. * @param {Node<float>} biasNode - The bias node.
  6744. * @return {TextureNode} A texture node representing the texture sample.
  6745. */
  6746. bias( biasNode ) {
  6747. const textureNode = this.clone();
  6748. textureNode.biasNode = nodeObject( biasNode );
  6749. textureNode.referenceNode = this.getSelf();
  6750. return nodeObject( textureNode );
  6751. }
  6752. /**
  6753. * Samples the texture by executing a compare operation.
  6754. *
  6755. * @param {Node<float>} compareNode - The node that defines the compare value.
  6756. * @return {TextureNode} A texture node representing the texture sample.
  6757. */
  6758. compare( compareNode ) {
  6759. const textureNode = this.clone();
  6760. textureNode.compareNode = nodeObject( compareNode );
  6761. textureNode.referenceNode = this.getSelf();
  6762. return nodeObject( textureNode );
  6763. }
  6764. /**
  6765. * Samples the texture using an explicit gradient.
  6766. *
  6767. * @param {Node<vec2>} gradNodeX - The gradX node.
  6768. * @param {Node<vec2>} gradNodeY - The gradY node.
  6769. * @return {TextureNode} A texture node representing the texture sample.
  6770. */
  6771. grad( gradNodeX, gradNodeY ) {
  6772. const textureNode = this.clone();
  6773. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6774. textureNode.referenceNode = this.getSelf();
  6775. return nodeObject( textureNode );
  6776. }
  6777. /**
  6778. * Samples the texture by defining a depth node.
  6779. *
  6780. * @param {Node<int>} depthNode - The depth node.
  6781. * @return {TextureNode} A texture node representing the texture sample.
  6782. */
  6783. depth( depthNode ) {
  6784. const textureNode = this.clone();
  6785. textureNode.depthNode = nodeObject( depthNode );
  6786. textureNode.referenceNode = this.getSelf();
  6787. return nodeObject( textureNode );
  6788. }
  6789. // --
  6790. serialize( data ) {
  6791. super.serialize( data );
  6792. data.value = this.value.toJSON( data.meta ).uuid;
  6793. data.sampler = this.sampler;
  6794. data.updateMatrix = this.updateMatrix;
  6795. data.updateType = this.updateType;
  6796. }
  6797. deserialize( data ) {
  6798. super.deserialize( data );
  6799. this.value = data.meta.textures[ data.value ];
  6800. this.sampler = data.sampler;
  6801. this.updateMatrix = data.updateMatrix;
  6802. this.updateType = data.updateType;
  6803. }
  6804. /**
  6805. * The update is used to implement the update of the uv transformation matrix.
  6806. */
  6807. update() {
  6808. const texture = this.value;
  6809. const matrixUniform = this._matrixUniform;
  6810. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6811. if ( texture.matrixAutoUpdate === true ) {
  6812. texture.updateMatrix();
  6813. }
  6814. }
  6815. /**
  6816. * Clones the texture node.
  6817. *
  6818. * @return {TextureNode} The cloned texture node.
  6819. */
  6820. clone() {
  6821. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6822. newNode.sampler = this.sampler;
  6823. return newNode;
  6824. }
  6825. }
  6826. /**
  6827. * TSL function for creating a texture node.
  6828. *
  6829. * @function
  6830. * @param {Texture} value - The texture.
  6831. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6832. * @param {Node<int>?} [levelNode=null] - The level node.
  6833. * @param {Node<float>?} [biasNode=null] - The bias node.
  6834. * @returns {TextureNode}
  6835. */
  6836. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6837. /**
  6838. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6839. *
  6840. * @function
  6841. * @param {Texture} value - The texture.
  6842. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6843. * @param {Node<int>?} [levelNode=null] - The level node.
  6844. * @param {Node<float>?} [biasNode=null] - The bias node.
  6845. * @returns {TextureNode}
  6846. */
  6847. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6848. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6849. /**
  6850. * Converts a texture or texture node to a sampler.
  6851. *
  6852. * @function
  6853. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6854. * @returns {Node}
  6855. */
  6856. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6857. /** @module BufferNode **/
  6858. /**
  6859. * A special type of uniform node which represents array-like data
  6860. * as uniform buffers. The access usually happens via `element()`
  6861. * which returns an instance of {@link ArrayElementNode}. For example:
  6862. *
  6863. * ```js
  6864. * const bufferNode = buffer( array, 'mat4', count );
  6865. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  6866. * ```
  6867. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  6868. * since it handles more input types and automatically cares about buffer paddings.
  6869. *
  6870. * @augments module:UniformNode~UniformNode
  6871. */
  6872. class BufferNode extends UniformNode {
  6873. static get type() {
  6874. return 'BufferNode';
  6875. }
  6876. /**
  6877. * Constructs a new buffer node.
  6878. *
  6879. * @param {Array<Number>} value - Array-like buffer data.
  6880. * @param {String} bufferType - The data type of the buffer.
  6881. * @param {Number} [bufferCount=0] - The count of buffer elements.
  6882. */
  6883. constructor( value, bufferType, bufferCount = 0 ) {
  6884. super( value, bufferType );
  6885. /**
  6886. * This flag can be used for type testing.
  6887. *
  6888. * @type {Boolean}
  6889. * @readonly
  6890. * @default true
  6891. */
  6892. this.isBufferNode = true;
  6893. /**
  6894. * The data type of the buffer.
  6895. *
  6896. * @type {String}
  6897. */
  6898. this.bufferType = bufferType;
  6899. /**
  6900. * The uniform node that holds the value of the reference node.
  6901. *
  6902. * @type {Number}
  6903. * @default 0
  6904. */
  6905. this.bufferCount = bufferCount;
  6906. }
  6907. /**
  6908. * The data type of the buffer elements.
  6909. *
  6910. * @param {NodeBuilder} builder - The current node builder.
  6911. * @return {String} The element type.
  6912. */
  6913. getElementType( builder ) {
  6914. return this.getNodeType( builder );
  6915. }
  6916. /**
  6917. * Overwrites the default implementation to return a fixed value `'buffer'`.
  6918. *
  6919. * @param {NodeBuilder} builder - The current node builder.
  6920. * @return {String} The input type.
  6921. */
  6922. getInputType( /*builder*/ ) {
  6923. return 'buffer';
  6924. }
  6925. }
  6926. /**
  6927. * TSL function for creating a buffer node.
  6928. *
  6929. * @function
  6930. * @param {Array} value - Array-like buffer data.
  6931. * @param {String} type - The data type of a buffer element.
  6932. * @param {Number} count - The count of buffer elements.
  6933. * @returns {BufferNode}
  6934. */
  6935. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  6936. /** @module UniformArrayNode **/
  6937. /**
  6938. * Represents the element access on uniform array nodes.
  6939. *
  6940. * @augments ArrayElementNode
  6941. */
  6942. class UniformArrayElementNode extends ArrayElementNode {
  6943. static get type() {
  6944. return 'UniformArrayElementNode';
  6945. }
  6946. /**
  6947. * Constructs a new buffer node.
  6948. *
  6949. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  6950. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  6951. */
  6952. constructor( uniformArrayNode, indexNode ) {
  6953. super( uniformArrayNode, indexNode );
  6954. /**
  6955. * This flag can be used for type testing.
  6956. *
  6957. * @type {Boolean}
  6958. * @readonly
  6959. * @default true
  6960. */
  6961. this.isArrayBufferElementNode = true;
  6962. }
  6963. generate( builder ) {
  6964. const snippet = super.generate( builder );
  6965. const type = this.getNodeType();
  6966. const paddedType = this.node.getPaddedType();
  6967. return builder.format( snippet, paddedType, type );
  6968. }
  6969. }
  6970. /**
  6971. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  6972. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  6973. * data types in the array (e.g `three.js` primitives) and automatically
  6974. * manage buffer padding. It should be the first choice when working with
  6975. * uniforms buffers.
  6976. * ```js
  6977. * const tintColors = uniformArray( [
  6978. * new Color( 1, 0, 0 ),
  6979. * new Color( 0, 1, 0 ),
  6980. * new Color( 0, 0, 1 )
  6981. * ], 'color' );
  6982. *
  6983. * const redColor = tintColors.element( 0 );
  6984. *
  6985. * @augments module:BufferNode~BufferNode
  6986. */
  6987. class UniformArrayNode extends BufferNode {
  6988. static get type() {
  6989. return 'UniformArrayNode';
  6990. }
  6991. /**
  6992. * Constructs a new uniform array node.
  6993. *
  6994. * @param {Array<Any>} value - Array holding the buffer data.
  6995. * @param {String?} [elementType=null] - The data type of a buffer element.
  6996. */
  6997. constructor( value, elementType = null ) {
  6998. super( null );
  6999. /**
  7000. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7001. * hold number primitives as well as three.js objects like vectors, matrices
  7002. * or colors.
  7003. *
  7004. * @type {Array<Any>}
  7005. */
  7006. this.array = value;
  7007. /**
  7008. * The data type of an array element.
  7009. *
  7010. * @type {String}
  7011. */
  7012. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7013. /**
  7014. * The padded type. Uniform buffers must conform to a certain buffer layout
  7015. * so a separate type is computed to ensure correct buffer size.
  7016. *
  7017. * @type {String}
  7018. */
  7019. this.paddedType = this.getPaddedType();
  7020. /**
  7021. * Overwritten since uniform array nodes are updated per render.
  7022. *
  7023. * @type {String}
  7024. * @default 'render'
  7025. */
  7026. this.updateType = NodeUpdateType.RENDER;
  7027. /**
  7028. * This flag can be used for type testing.
  7029. *
  7030. * @type {Boolean}
  7031. * @readonly
  7032. * @default true
  7033. */
  7034. this.isArrayBufferNode = true;
  7035. }
  7036. /**
  7037. * This method is overwritten since the node type is inferred from the
  7038. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7039. *
  7040. * @param {NodeBuilder} builder - The current node builder.
  7041. * @return {String} The node type.
  7042. */
  7043. getNodeType( /*builder*/ ) {
  7044. return this.paddedType;
  7045. }
  7046. /**
  7047. * The data type of the array elements.
  7048. *
  7049. * @param {NodeBuilder} builder - The current node builder.
  7050. * @return {String} The element type.
  7051. */
  7052. getElementType() {
  7053. return this.elementType;
  7054. }
  7055. /**
  7056. * Returns the padded type based on the element type.
  7057. *
  7058. * @return {String} The padded type.
  7059. */
  7060. getPaddedType() {
  7061. const elementType = this.elementType;
  7062. let paddedType = 'vec4';
  7063. if ( elementType === 'mat2' ) {
  7064. paddedType = 'mat2';
  7065. } else if ( /mat/.test( elementType ) === true ) {
  7066. paddedType = 'mat4';
  7067. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7068. paddedType = 'ivec4';
  7069. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7070. paddedType = 'uvec4';
  7071. }
  7072. return paddedType;
  7073. }
  7074. /**
  7075. * The update makes sure to correctly transfer the data from the (complex) objects
  7076. * in the array to the internal, correctly padded value buffer.
  7077. *
  7078. * @param {NodeFrame} frame - A reference to the current node frame.
  7079. */
  7080. update( /*frame*/ ) {
  7081. const { array, value } = this;
  7082. const elementType = this.elementType;
  7083. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7084. for ( let i = 0; i < array.length; i ++ ) {
  7085. const index = i * 4;
  7086. value[ index ] = array[ i ];
  7087. }
  7088. } else if ( elementType === 'color' ) {
  7089. for ( let i = 0; i < array.length; i ++ ) {
  7090. const index = i * 4;
  7091. const vector = array[ i ];
  7092. value[ index ] = vector.r;
  7093. value[ index + 1 ] = vector.g;
  7094. value[ index + 2 ] = vector.b || 0;
  7095. //value[ index + 3 ] = vector.a || 0;
  7096. }
  7097. } else if ( elementType === 'mat2' ) {
  7098. for ( let i = 0; i < array.length; i ++ ) {
  7099. const index = i * 4;
  7100. const matrix = array[ i ];
  7101. value[ index ] = matrix.elements[ 0 ];
  7102. value[ index + 1 ] = matrix.elements[ 1 ];
  7103. value[ index + 2 ] = matrix.elements[ 2 ];
  7104. value[ index + 3 ] = matrix.elements[ 3 ];
  7105. }
  7106. } else if ( elementType === 'mat3' ) {
  7107. for ( let i = 0; i < array.length; i ++ ) {
  7108. const index = i * 16;
  7109. const matrix = array[ i ];
  7110. value[ index ] = matrix.elements[ 0 ];
  7111. value[ index + 1 ] = matrix.elements[ 1 ];
  7112. value[ index + 2 ] = matrix.elements[ 2 ];
  7113. value[ index + 4 ] = matrix.elements[ 3 ];
  7114. value[ index + 5 ] = matrix.elements[ 4 ];
  7115. value[ index + 6 ] = matrix.elements[ 5 ];
  7116. value[ index + 8 ] = matrix.elements[ 6 ];
  7117. value[ index + 9 ] = matrix.elements[ 7 ];
  7118. value[ index + 10 ] = matrix.elements[ 8 ];
  7119. value[ index + 15 ] = 1;
  7120. }
  7121. } else if ( elementType === 'mat4' ) {
  7122. for ( let i = 0; i < array.length; i ++ ) {
  7123. const index = i * 16;
  7124. const matrix = array[ i ];
  7125. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7126. value[ index + i ] = matrix.elements[ i ];
  7127. }
  7128. }
  7129. } else {
  7130. for ( let i = 0; i < array.length; i ++ ) {
  7131. const index = i * 4;
  7132. const vector = array[ i ];
  7133. value[ index ] = vector.x;
  7134. value[ index + 1 ] = vector.y;
  7135. value[ index + 2 ] = vector.z || 0;
  7136. value[ index + 3 ] = vector.w || 0;
  7137. }
  7138. }
  7139. }
  7140. /**
  7141. * Implement the value buffer creation based on the array data.
  7142. *
  7143. * @param {NodeBuilder} builder - A reference to the current node builder.
  7144. * @return {null}
  7145. */
  7146. setup( builder ) {
  7147. const length = this.array.length;
  7148. const elementType = this.elementType;
  7149. let arrayType = Float32Array;
  7150. const paddedType = this.paddedType;
  7151. const paddedElementLength = builder.getTypeLength( paddedType );
  7152. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7153. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7154. this.value = new arrayType( length * paddedElementLength );
  7155. this.bufferCount = length;
  7156. this.bufferType = paddedType;
  7157. return super.setup( builder );
  7158. }
  7159. /**
  7160. * Overwrites the default `element()` method to provide element access
  7161. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7162. *
  7163. * @param {IndexNode} indexNode - The index node.
  7164. * @return {UniformArrayElementNode}
  7165. */
  7166. element( indexNode ) {
  7167. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7168. }
  7169. }
  7170. /**
  7171. * TSL function for creating an uniform array node.
  7172. *
  7173. * @function
  7174. * @param {Array<Any>} values - Array-like data.
  7175. * @param {String?} nodeType - The data type of the array elements.
  7176. * @returns {UniformArrayNode}
  7177. */
  7178. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7179. /**
  7180. * @function
  7181. * @deprecated since r168. Use {@link uniformArray} instead.
  7182. *
  7183. * @param {Array<Any>} values - Array-like data.
  7184. * @param {String} nodeType - The data type of the array elements.
  7185. * @returns {UniformArrayNode}
  7186. */
  7187. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7188. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7189. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7190. };
  7191. /** @module Camera **/
  7192. /**
  7193. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7194. *
  7195. * @type {UniformNode<uint>}
  7196. */
  7197. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7198. /**
  7199. * TSL object that represents the `near` value of the camera used for the current render.
  7200. *
  7201. * @type {UniformNode<float>}
  7202. */
  7203. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7204. /**
  7205. * TSL object that represents the `far` value of the camera used for the current render.
  7206. *
  7207. * @type {UniformNode<float>}
  7208. */
  7209. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7210. /**
  7211. * TSL object that represents the projection matrix of the camera used for the current render.
  7212. *
  7213. * @type {UniformNode<mat4>}
  7214. */
  7215. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7216. let cameraProjectionMatrix;
  7217. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7218. const matrices = [];
  7219. for ( const subCamera of camera.cameras ) {
  7220. matrices.push( subCamera.projectionMatrix );
  7221. }
  7222. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7223. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7224. } else {
  7225. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7226. }
  7227. return cameraProjectionMatrix;
  7228. } ).once() )();
  7229. /**
  7230. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7231. *
  7232. * @type {UniformNode<mat4>}
  7233. */
  7234. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7235. /**
  7236. * TSL object that represents the view matrix of the camera used for the current render.
  7237. *
  7238. * @type {UniformNode<mat4>}
  7239. */
  7240. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7241. let cameraViewMatrix;
  7242. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7243. const matrices = [];
  7244. for ( const subCamera of camera.cameras ) {
  7245. matrices.push( subCamera.matrixWorldInverse );
  7246. }
  7247. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7248. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7249. } else {
  7250. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7251. }
  7252. return cameraViewMatrix;
  7253. } ).once() )();
  7254. /**
  7255. * TSL object that represents the world matrix of the camera used for the current render.
  7256. *
  7257. * @type {UniformNode<mat4>}
  7258. */
  7259. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7260. /**
  7261. * TSL object that represents the normal matrix of the camera used for the current render.
  7262. *
  7263. * @type {UniformNode<mat3>}
  7264. */
  7265. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7266. /**
  7267. * TSL object that represents the position in world space of the camera used for the current render.
  7268. *
  7269. * @type {UniformNode<vec3>}
  7270. */
  7271. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7272. /** @module Object3DNode **/
  7273. /**
  7274. * This node can be used to access transformation related metrics of 3D objects.
  7275. * Depending on the selected scope, a different metric is represented as a uniform
  7276. * in the shader. The following scopes are supported:
  7277. *
  7278. * - `POSITION`: The object's position in world space.
  7279. * - `VIEW_POSITION`: The object's position in view/camera space.
  7280. * - `DIRECTION`: The object's direction in world space.
  7281. * - `SCALE`: The object's scale in world space.
  7282. * - `WORLD_MATRIX`: The object's matrix in world space.
  7283. *
  7284. * @augments Node
  7285. */
  7286. class Object3DNode extends Node {
  7287. static get type() {
  7288. return 'Object3DNode';
  7289. }
  7290. /**
  7291. * Constructs a new object 3D node.
  7292. *
  7293. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7294. * @param {Object3D?} [object3d=null] - The 3D object.
  7295. */
  7296. constructor( scope, object3d = null ) {
  7297. super();
  7298. /**
  7299. * The node reports a different type of transformation depending on the scope.
  7300. *
  7301. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7302. */
  7303. this.scope = scope;
  7304. /**
  7305. * The 3D object.
  7306. *
  7307. * @type {Object3D?}
  7308. * @default null
  7309. */
  7310. this.object3d = object3d;
  7311. /**
  7312. * Overwritten since this type of node is updated per object.
  7313. *
  7314. * @type {String}
  7315. * @default 'object'
  7316. */
  7317. this.updateType = NodeUpdateType.OBJECT;
  7318. /**
  7319. * Holds the value of the node as a uniform.
  7320. *
  7321. * @private
  7322. * @type {UniformNode}
  7323. */
  7324. this._uniformNode = new UniformNode( null );
  7325. }
  7326. /**
  7327. * Overwritten since the node type is inferred from the scope.
  7328. *
  7329. * @return {String} The node type.
  7330. */
  7331. getNodeType() {
  7332. const scope = this.scope;
  7333. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7334. return 'mat4';
  7335. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7336. return 'vec3';
  7337. }
  7338. }
  7339. /**
  7340. * Updates the uniform value depending on the scope.
  7341. *
  7342. * @param {NodeFrame} frame - The current node frame.
  7343. */
  7344. update( frame ) {
  7345. const object = this.object3d;
  7346. const uniformNode = this._uniformNode;
  7347. const scope = this.scope;
  7348. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7349. uniformNode.value = object.matrixWorld;
  7350. } else if ( scope === Object3DNode.POSITION ) {
  7351. uniformNode.value = uniformNode.value || new Vector3();
  7352. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7353. } else if ( scope === Object3DNode.SCALE ) {
  7354. uniformNode.value = uniformNode.value || new Vector3();
  7355. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7356. } else if ( scope === Object3DNode.DIRECTION ) {
  7357. uniformNode.value = uniformNode.value || new Vector3();
  7358. object.getWorldDirection( uniformNode.value );
  7359. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7360. const camera = frame.camera;
  7361. uniformNode.value = uniformNode.value || new Vector3();
  7362. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7363. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7364. }
  7365. }
  7366. /**
  7367. * Generates the code snippet of the uniform node. The node type of the uniform
  7368. * node also depends on the selected scope.
  7369. *
  7370. * @param {NodeBuilder} builder - The current node builder.
  7371. * @return {String} The generated code snippet.
  7372. */
  7373. generate( builder ) {
  7374. const scope = this.scope;
  7375. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7376. this._uniformNode.nodeType = 'mat4';
  7377. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7378. this._uniformNode.nodeType = 'vec3';
  7379. }
  7380. return this._uniformNode.build( builder );
  7381. }
  7382. serialize( data ) {
  7383. super.serialize( data );
  7384. data.scope = this.scope;
  7385. }
  7386. deserialize( data ) {
  7387. super.deserialize( data );
  7388. this.scope = data.scope;
  7389. }
  7390. }
  7391. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7392. Object3DNode.POSITION = 'position';
  7393. Object3DNode.SCALE = 'scale';
  7394. Object3DNode.VIEW_POSITION = 'viewPosition';
  7395. Object3DNode.DIRECTION = 'direction';
  7396. /**
  7397. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7398. *
  7399. * @function
  7400. * @param {Object3D?} [object3d=null] - The 3D object.
  7401. * @returns {Object3DNode<vec3>}
  7402. */
  7403. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7404. /**
  7405. * TSL function for creating an object 3D node that represents the object's world matrix.
  7406. *
  7407. * @function
  7408. * @param {Object3D?} [object3d=null] - The 3D object.
  7409. * @returns {Object3DNode<mat4>}
  7410. */
  7411. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7412. /**
  7413. * TSL function for creating an object 3D node that represents the object's position in world space.
  7414. *
  7415. * @function
  7416. * @param {Object3D?} [object3d=null] - The 3D object.
  7417. * @returns {Object3DNode<vec3>}
  7418. */
  7419. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7420. /**
  7421. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7422. *
  7423. * @function
  7424. * @param {Object3D?} [object3d=null] - The 3D object.
  7425. * @returns {Object3DNode<vec3>}
  7426. */
  7427. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7428. /**
  7429. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7430. *
  7431. * @function
  7432. * @param {Object3D?} [object3d=null] - The 3D object.
  7433. * @returns {Object3DNode<vec3>}
  7434. */
  7435. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7436. /** @module ModelNode **/
  7437. /**
  7438. * This type of node is a specialized version of `Object3DNode`
  7439. * with larger set of model related metrics. Unlike `Object3DNode`,
  7440. * `ModelNode` extracts the reference to the 3D object from the
  7441. * current node frame state.
  7442. *
  7443. * @augments module:Object3DNode~Object3DNode
  7444. */
  7445. class ModelNode extends Object3DNode {
  7446. static get type() {
  7447. return 'ModelNode';
  7448. }
  7449. /**
  7450. * Constructs a new object model node.
  7451. *
  7452. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7453. */
  7454. constructor( scope ) {
  7455. super( scope );
  7456. }
  7457. /**
  7458. * Extracts the model reference from the frame state and then
  7459. * updates the uniform value depending on the scope.
  7460. *
  7461. * @param {NodeFrame} frame - The current node frame.
  7462. */
  7463. update( frame ) {
  7464. this.object3d = frame.object;
  7465. super.update( frame );
  7466. }
  7467. }
  7468. /**
  7469. * TSL object that represents the object's direction in world space.
  7470. *
  7471. * @type {ModelNode<vec3>}
  7472. */
  7473. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7474. /**
  7475. * TSL object that represents the object's world matrix.
  7476. *
  7477. * @type {ModelNode<mat4>}
  7478. */
  7479. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7480. /**
  7481. * TSL object that represents the object's position in world space.
  7482. *
  7483. * @type {ModelNode<vec3>}
  7484. */
  7485. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7486. /**
  7487. * TSL object that represents the object's scale in world space.
  7488. *
  7489. * @type {ModelNode<vec3>}
  7490. */
  7491. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7492. /**
  7493. * TSL object that represents the object's position in view/camera space.
  7494. *
  7495. * @type {ModelNode<vec3>}
  7496. */
  7497. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7498. /**
  7499. * TSL object that represents the object's normal matrix.
  7500. *
  7501. * @type {UniformNode<mat3>}
  7502. */
  7503. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7504. /**
  7505. * TSL object that represents the object's inverse world matrix.
  7506. *
  7507. * @type {UniformNode<mat4>}
  7508. */
  7509. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7510. /**
  7511. * TSL object that represents the object's model view matrix.
  7512. *
  7513. * @type {Node<mat4>}
  7514. */
  7515. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7516. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7517. } ).once() )().toVar( 'modelViewMatrix' );
  7518. // GPU Precision
  7519. /**
  7520. * TSL object that represents the object's model view in `mediump` precision.
  7521. *
  7522. * @type {Node<mat4>}
  7523. */
  7524. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7525. // CPU Precision
  7526. /**
  7527. * TSL object that represents the object's model view in `highp` precision
  7528. * which is achieved by computing the matrix in JS and not in the shader.
  7529. *
  7530. * @type {Node<mat4>}
  7531. */
  7532. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7533. builder.context.isHighPrecisionModelViewMatrix = true;
  7534. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7535. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7536. } );
  7537. } ).once() )().toVar( 'highpModelViewMatrix' );
  7538. /**
  7539. * TSL object that represents the object's model normal view in `highp` precision
  7540. * which is achieved by computing the matrix in JS and not in the shader.
  7541. *
  7542. * @type {Node<mat3>}
  7543. */
  7544. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7545. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7546. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7547. if ( isHighPrecisionModelViewMatrix !== true ) {
  7548. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7549. }
  7550. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7551. } );
  7552. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7553. /** @module Position **/
  7554. /**
  7555. * TSL object that represents the position attribute of the current rendered object.
  7556. *
  7557. * @type {AttributeNode<vec3>}
  7558. */
  7559. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7560. /**
  7561. * TSL object that represents the vertex position in local space of the current rendered object.
  7562. *
  7563. * @type {AttributeNode<vec3>}
  7564. */
  7565. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7566. /**
  7567. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7568. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7569. *
  7570. * @type {AttributeNode<vec3>}
  7571. */
  7572. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7573. /**
  7574. * TSL object that represents the vertex position in world space of the current rendered object.
  7575. *
  7576. * @type {VaryingNode<vec3>}
  7577. */
  7578. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7579. /**
  7580. * TSL object that represents the position world direction of the current rendered object.
  7581. *
  7582. * @type {Node<vec3>}
  7583. */
  7584. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7585. /**
  7586. * TSL object that represents the vertex position in view space of the current rendered object.
  7587. *
  7588. * @type {VaryingNode<vec3>}
  7589. */
  7590. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7591. return builder.context.setupPositionView();
  7592. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7593. /**
  7594. * TSL object that represents the position view direction of the current rendered object.
  7595. *
  7596. * @type {VaryingNode<vec3>}
  7597. */
  7598. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7599. /** @module FrontFacingNode **/
  7600. /**
  7601. * This node can be used to evaluate whether a primitive is front or back facing.
  7602. *
  7603. * @augments Node
  7604. */
  7605. class FrontFacingNode extends Node {
  7606. static get type() {
  7607. return 'FrontFacingNode';
  7608. }
  7609. /**
  7610. * Constructs a new front facing node.
  7611. */
  7612. constructor() {
  7613. super( 'bool' );
  7614. /**
  7615. * This flag can be used for type testing.
  7616. *
  7617. * @type {Boolean}
  7618. * @readonly
  7619. * @default true
  7620. */
  7621. this.isFrontFacingNode = true;
  7622. }
  7623. generate( builder ) {
  7624. const { renderer, material } = builder;
  7625. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7626. if ( material.side === BackSide ) {
  7627. return 'false';
  7628. }
  7629. }
  7630. return builder.getFrontFacing();
  7631. }
  7632. }
  7633. /**
  7634. * TSL object that represents whether a primitive is front or back facing
  7635. *
  7636. * @type {FrontFacingNode<bool>}
  7637. */
  7638. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7639. /**
  7640. * TSL object that represents the front facing status as a number instead of a bool.
  7641. * `1` means front facing, `-1` means back facing.
  7642. *
  7643. * @type {Node<float>}
  7644. */
  7645. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7646. /** @module Normal **/
  7647. /**
  7648. * TSL object that represents the normal attribute of the current rendered object.
  7649. *
  7650. * @type {Node<vec3>}
  7651. */
  7652. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7653. /**
  7654. * TSL object that represents the vertex normal in local space of the current rendered object.
  7655. *
  7656. * @type {Node<vec3>}
  7657. */
  7658. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7659. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7660. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7661. return vec3( 0, 1, 0 );
  7662. }
  7663. return normalGeometry;
  7664. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7665. /**
  7666. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7667. *
  7668. * @type {Node<vec3>}
  7669. */
  7670. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7671. /**
  7672. * TSL object that represents the vertex normal in view space of the current rendered object.
  7673. *
  7674. * @type {Node<vec3>}
  7675. */
  7676. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7677. let node;
  7678. if ( builder.material.flatShading === true ) {
  7679. node = normalFlat;
  7680. } else {
  7681. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7682. }
  7683. return node;
  7684. }, 'vec3' ).once() )().toVar( 'normalView' );
  7685. /**
  7686. * TSL object that represents the vertex normal in world space of the current rendered object.
  7687. *
  7688. * @type {Node<vec3>}
  7689. */
  7690. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7691. /**
  7692. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7693. *
  7694. * @type {Node<vec3>}
  7695. */
  7696. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7697. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7698. return builder.context.setupNormal().context( { getUV: null } );
  7699. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7700. /**
  7701. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7702. *
  7703. * @type {Node<vec3>}
  7704. */
  7705. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7706. /**
  7707. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7708. *
  7709. * @type {Node<vec3>}
  7710. */
  7711. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7712. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7713. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7714. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7715. /**
  7716. * Transforms the normal with the given matrix.
  7717. *
  7718. * @function
  7719. * @param {Node<vec3>} normal - The normal.
  7720. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7721. * @return {Node<vec3>} The transformed normal.
  7722. */
  7723. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7724. const m = mat3( matrix );
  7725. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7726. return m.mul( transformedNormal ).xyz;
  7727. } );
  7728. /**
  7729. * Transforms the given normal from local to view space.
  7730. *
  7731. * @function
  7732. * @param {Node<vec3>} normal - The normal.
  7733. * @param {NodeBuilder} builder - The current node builder.
  7734. * @return {Node<vec3>} The transformed normal.
  7735. */
  7736. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7737. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7738. if ( modelNormalViewMatrix !== null ) {
  7739. return modelNormalViewMatrix.transformDirection( normal );
  7740. }
  7741. //
  7742. const transformedNormal = modelNormalMatrix.mul( normal );
  7743. return cameraViewMatrix.transformDirection( transformedNormal );
  7744. } );
  7745. /** @module MaterialProperties **/
  7746. /**
  7747. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7748. *
  7749. * @type {UniformNode<float>}
  7750. */
  7751. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7752. /** @module ReflectVector **/
  7753. /**
  7754. * The reflect vector in view space.
  7755. *
  7756. * @type {Node<vec3>}
  7757. */
  7758. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7759. /**
  7760. * The refract vector in view space.
  7761. *
  7762. * @type {Node<vec3>}
  7763. */
  7764. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7765. /**
  7766. * Used for sampling cube maps when using cube reflection mapping.
  7767. *
  7768. * @type {Node<vec3>}
  7769. */
  7770. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7771. /**
  7772. * Used for sampling cube maps when using cube refraction mapping.
  7773. *
  7774. * @type {Node<vec3>}
  7775. */
  7776. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7777. /** @module CubeTextureNode **/
  7778. /**
  7779. * This type of uniform node represents a cube texture.
  7780. *
  7781. * @augments module:TextureNode~TextureNode
  7782. */
  7783. class CubeTextureNode extends TextureNode {
  7784. static get type() {
  7785. return 'CubeTextureNode';
  7786. }
  7787. /**
  7788. * Constructs a new cube texture node.
  7789. *
  7790. * @param {CubeTexture} value - The cube texture.
  7791. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7792. * @param {Node<int>?} [levelNode=null] - The level node.
  7793. * @param {Node<float>?} [biasNode=null] - The bias node.
  7794. */
  7795. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7796. super( value, uvNode, levelNode, biasNode );
  7797. /**
  7798. * This flag can be used for type testing.
  7799. *
  7800. * @type {Boolean}
  7801. * @readonly
  7802. * @default true
  7803. */
  7804. this.isCubeTextureNode = true;
  7805. }
  7806. /**
  7807. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7808. *
  7809. * @param {NodeBuilder} builder - The current node builder.
  7810. * @return {String} The input type.
  7811. */
  7812. getInputType( /*builder*/ ) {
  7813. return 'cubeTexture';
  7814. }
  7815. /**
  7816. * Returns a default uvs based on the mapping type of the cube texture.
  7817. *
  7818. * @return {Node<vec3>} The default uv attribute.
  7819. */
  7820. getDefaultUV() {
  7821. const texture = this.value;
  7822. if ( texture.mapping === CubeReflectionMapping ) {
  7823. return reflectVector;
  7824. } else if ( texture.mapping === CubeRefractionMapping ) {
  7825. return refractVector;
  7826. } else {
  7827. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7828. return vec3( 0, 0, 0 );
  7829. }
  7830. }
  7831. /**
  7832. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7833. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7834. *
  7835. * @param {Boolean} value - The update toggle.
  7836. */
  7837. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7838. /**
  7839. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7840. * to modify the uv node for correct sampling.
  7841. *
  7842. * @param {NodeBuilder} builder - The current node builder.
  7843. * @param {Node} uvNode - The uv node to setup.
  7844. * @return {Node} The updated uv node.
  7845. */
  7846. setupUV( builder, uvNode ) {
  7847. const texture = this.value;
  7848. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7849. return vec3( uvNode.x.negate(), uvNode.yz );
  7850. } else {
  7851. return uvNode;
  7852. }
  7853. }
  7854. /**
  7855. * Generates the uv code snippet.
  7856. *
  7857. * @param {NodeBuilder} builder - The current node builder.
  7858. * @param {Node} cubeUV - The uv node to generate code for.
  7859. * @return {String} The generated code snippet.
  7860. */
  7861. generateUV( builder, cubeUV ) {
  7862. return cubeUV.build( builder, 'vec3' );
  7863. }
  7864. }
  7865. /**
  7866. * TSL function for creating a cube texture node.
  7867. *
  7868. * @function
  7869. * @param {CubeTexture} value - The cube texture.
  7870. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7871. * @param {Node<int>?} [levelNode=null] - The level node.
  7872. * @param {Node<float>?} [biasNode=null] - The bias node.
  7873. * @returns {CubeTextureNode}
  7874. */
  7875. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7876. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7877. /** @module ReferenceNode **/
  7878. /**
  7879. * This class is only relevant if the referenced property is array-like.
  7880. * In this case, `ReferenceElementNode` allows to refer to a specific
  7881. * element inside the data structure via an index.
  7882. *
  7883. * @augments ArrayElementNode
  7884. */
  7885. class ReferenceElementNode extends ArrayElementNode {
  7886. static get type() {
  7887. return 'ReferenceElementNode';
  7888. }
  7889. /**
  7890. * Constructs a new reference element node.
  7891. *
  7892. * @param {ReferenceNode?} referenceNode - The reference node.
  7893. * @param {Node} indexNode - The index node that defines the element access.
  7894. */
  7895. constructor( referenceNode, indexNode ) {
  7896. super( referenceNode, indexNode );
  7897. /**
  7898. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7899. * property references to the current node.
  7900. *
  7901. * @type {ReferenceNode?}
  7902. * @default null
  7903. */
  7904. this.referenceNode = referenceNode;
  7905. /**
  7906. * This flag can be used for type testing.
  7907. *
  7908. * @type {Boolean}
  7909. * @readonly
  7910. * @default true
  7911. */
  7912. this.isReferenceElementNode = true;
  7913. }
  7914. /**
  7915. * This method is overwritten since the node type is inferred from
  7916. * the uniform type of the reference node.
  7917. *
  7918. * @return {String} The node type.
  7919. */
  7920. getNodeType() {
  7921. return this.referenceNode.uniformType;
  7922. }
  7923. generate( builder ) {
  7924. const snippet = super.generate( builder );
  7925. const arrayType = this.referenceNode.getNodeType();
  7926. const elementType = this.getNodeType();
  7927. return builder.format( snippet, arrayType, elementType );
  7928. }
  7929. }
  7930. /**
  7931. * This type of node establishes a reference to a property of another object.
  7932. * In this way, the value of the node is automatically linked to the value of
  7933. * referenced object. Reference nodes internally represent the linked value
  7934. * as a uniform.
  7935. *
  7936. * @augments Node
  7937. */
  7938. class ReferenceNode extends Node {
  7939. static get type() {
  7940. return 'ReferenceNode';
  7941. }
  7942. /**
  7943. * Constructs a new reference node.
  7944. *
  7945. * @param {String} property - The name of the property the node refers to.
  7946. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7947. * @param {Object?} [object=null] - The object the property belongs to.
  7948. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7949. */
  7950. constructor( property, uniformType, object = null, count = null ) {
  7951. super();
  7952. /**
  7953. * The name of the property the node refers to.
  7954. *
  7955. * @type {String}
  7956. */
  7957. this.property = property;
  7958. /**
  7959. * The uniform type that should be used to represent the property value.
  7960. *
  7961. * @type {String}
  7962. */
  7963. this.uniformType = uniformType;
  7964. /**
  7965. * The object the property belongs to.
  7966. *
  7967. * @type {Object?}
  7968. * @default null
  7969. */
  7970. this.object = object;
  7971. /**
  7972. * When the linked property is an array, this parameter defines its length.
  7973. *
  7974. * @type {Number?}
  7975. * @default null
  7976. */
  7977. this.count = count;
  7978. /**
  7979. * The property name might have dots so nested properties can be referred.
  7980. * The hierarchy of the names is stored inside this array.
  7981. *
  7982. * @type {Array<String>}
  7983. */
  7984. this.properties = property.split( '.' );
  7985. /**
  7986. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7987. * since the final reference might be updated from calling code.
  7988. *
  7989. * @type {Object?}
  7990. * @default null
  7991. */
  7992. this.reference = object;
  7993. /**
  7994. * The uniform node that holds the value of the reference node.
  7995. *
  7996. * @type {UniformNode}
  7997. * @default null
  7998. */
  7999. this.node = null;
  8000. /**
  8001. * The uniform group of the internal uniform.
  8002. *
  8003. * @type {UniformGroupNode}
  8004. * @default null
  8005. */
  8006. this.group = null;
  8007. /**
  8008. * An optional label of the internal uniform node.
  8009. *
  8010. * @type {String?}
  8011. * @default null
  8012. */
  8013. this.name = null;
  8014. /**
  8015. * Overwritten since reference nodes are updated per object.
  8016. *
  8017. * @type {String}
  8018. * @default 'object'
  8019. */
  8020. this.updateType = NodeUpdateType.OBJECT;
  8021. }
  8022. /**
  8023. * When the referred property is array-like, this method can be used
  8024. * to access elements via an index node.
  8025. *
  8026. * @param {IndexNode} indexNode - indexNode.
  8027. * @return {ReferenceElementNode} A reference to an element.
  8028. */
  8029. element( indexNode ) {
  8030. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8031. }
  8032. /**
  8033. * Sets the uniform group for this reference node.
  8034. *
  8035. * @param {UniformGroupNode} group - The uniform group to set.
  8036. * @return {ReferenceNode} A reference to this node.
  8037. */
  8038. setGroup( group ) {
  8039. this.group = group;
  8040. return this;
  8041. }
  8042. /**
  8043. * Sets the label for the internal uniform.
  8044. *
  8045. * @param {String} name - The label to set.
  8046. * @return {ReferenceNode} A reference to this node.
  8047. */
  8048. label( name ) {
  8049. this.name = name;
  8050. return this;
  8051. }
  8052. /**
  8053. * Sets the node type which automatically defines the internal
  8054. * uniform type.
  8055. *
  8056. * @param {String} uniformType - The type to set.
  8057. */
  8058. setNodeType( uniformType ) {
  8059. let node = null;
  8060. if ( this.count !== null ) {
  8061. node = buffer( null, uniformType, this.count );
  8062. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8063. node = uniformArray( null, uniformType );
  8064. } else if ( uniformType === 'texture' ) {
  8065. node = texture( null );
  8066. } else if ( uniformType === 'cubeTexture' ) {
  8067. node = cubeTexture( null );
  8068. } else {
  8069. node = uniform( null, uniformType );
  8070. }
  8071. if ( this.group !== null ) {
  8072. node.setGroup( this.group );
  8073. }
  8074. if ( this.name !== null ) node.label( this.name );
  8075. this.node = node.getSelf();
  8076. }
  8077. /**
  8078. * This method is overwritten since the node type is inferred from
  8079. * the type of the reference node.
  8080. *
  8081. * @param {NodeBuilder} builder - The current node builder.
  8082. * @return {String} The node type.
  8083. */
  8084. getNodeType( builder ) {
  8085. if ( this.node === null ) {
  8086. this.updateReference( builder );
  8087. this.updateValue();
  8088. }
  8089. return this.node.getNodeType( builder );
  8090. }
  8091. /**
  8092. * Returns the property value from the given referred object.
  8093. *
  8094. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8095. * @return {Any} The value.
  8096. */
  8097. getValueFromReference( object = this.reference ) {
  8098. const { properties } = this;
  8099. let value = object[ properties[ 0 ] ];
  8100. for ( let i = 1; i < properties.length; i ++ ) {
  8101. value = value[ properties[ i ] ];
  8102. }
  8103. return value;
  8104. }
  8105. /**
  8106. * Allows to update the reference based on the given state. The state is only
  8107. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8108. *
  8109. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8110. * @return {Object} The updated reference.
  8111. */
  8112. updateReference( state ) {
  8113. this.reference = this.object !== null ? this.object : state.object;
  8114. return this.reference;
  8115. }
  8116. /**
  8117. * The output of the reference node is the internal uniform node.
  8118. *
  8119. * @param {NodeBuilder} builder - The current node builder.
  8120. * @return {UniformNode} The output node.
  8121. */
  8122. setup( /* builder */ ) {
  8123. this.updateValue();
  8124. return this.node;
  8125. }
  8126. /**
  8127. * Overwritten to to update the internal uniform value.
  8128. *
  8129. * @param {NodeFrame} frame - A reference to the current node frame.
  8130. */
  8131. update( /*frame*/ ) {
  8132. this.updateValue();
  8133. }
  8134. /**
  8135. * Retrieves the value from the referred object property and uses it
  8136. * to updated the internal uniform.
  8137. */
  8138. updateValue() {
  8139. if ( this.node === null ) this.setNodeType( this.uniformType );
  8140. const value = this.getValueFromReference();
  8141. if ( Array.isArray( value ) ) {
  8142. this.node.array = value;
  8143. } else {
  8144. this.node.value = value;
  8145. }
  8146. }
  8147. }
  8148. /**
  8149. * TSL function for creating a reference node.
  8150. *
  8151. * @function
  8152. * @param {String} name - The name of the property the node refers to.
  8153. * @param {String} type - The uniform type that should be used to represent the property value.
  8154. * @param {Object} object - The object the property belongs to.
  8155. * @returns {ReferenceNode}
  8156. */
  8157. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8158. /**
  8159. * TSL function for creating a reference node. Use this function if you want need a reference
  8160. * to an array-like property that should be represented as a uniform buffer.
  8161. *
  8162. * @function
  8163. * @param {String} name - The name of the property the node refers to.
  8164. * @param {String} type - The uniform type that should be used to represent the property value.
  8165. * @param {Number} count - The number of value inside the array-like object.
  8166. * @param {Object} object - An array-like object the property belongs to.
  8167. * @returns {ReferenceNode}
  8168. */
  8169. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8170. /** @module MaterialReferenceNode **/
  8171. /**
  8172. * This node is a special type of reference node which is intended
  8173. * for linking material properties with node values.
  8174. * ```js
  8175. * const opacityNode = materialReference( 'opacity', 'float', material );
  8176. * ```
  8177. * When changing `material.opacity`, the node value of `opacityNode` will
  8178. * automatically be updated.
  8179. *
  8180. * @augments module:ReferenceNode~ReferenceNode
  8181. */
  8182. class MaterialReferenceNode extends ReferenceNode {
  8183. static get type() {
  8184. return 'MaterialReferenceNode';
  8185. }
  8186. /**
  8187. * Constructs a new material reference node.
  8188. *
  8189. * @param {String} property - The name of the property the node refers to.
  8190. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8191. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8192. * the node refers to the material of the current rendered object.
  8193. */
  8194. constructor( property, inputType, material = null ) {
  8195. super( property, inputType, material );
  8196. /**
  8197. * The material the property belongs to. When no material is set,
  8198. * the node refers to the material of the current rendered object.
  8199. *
  8200. * @type {Material?}
  8201. * @default null
  8202. */
  8203. this.material = material;
  8204. /**
  8205. * This flag can be used for type testing.
  8206. *
  8207. * @type {Boolean}
  8208. * @readonly
  8209. * @default true
  8210. */
  8211. this.isMaterialReferenceNode = true;
  8212. }
  8213. /**
  8214. * Updates the reference based on the given state. The state is only evaluated
  8215. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8216. *
  8217. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8218. * @return {Object} The updated reference.
  8219. */
  8220. updateReference( state ) {
  8221. this.reference = this.material !== null ? this.material : state.material;
  8222. return this.reference;
  8223. }
  8224. }
  8225. /**
  8226. * TSL function for creating a material reference node.
  8227. *
  8228. * @function
  8229. * @param {String} name - The name of the property the node refers to.
  8230. * @param {String} type - The uniform type that should be used to represent the property value.
  8231. * @param {Material?} [material=null] - The material the property belongs to.
  8232. * When no material is set, the node refers to the material of the current rendered object.
  8233. * @returns {MaterialReferenceNode}
  8234. */
  8235. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8236. /** @module Tangent **/
  8237. /**
  8238. * TSL object that represents the tangent attribute of the current rendered object.
  8239. *
  8240. * @type {Node<vec4>}
  8241. */
  8242. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8243. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8244. builder.geometry.computeTangents();
  8245. }
  8246. return attribute( 'tangent', 'vec4' );
  8247. } )();
  8248. /**
  8249. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8250. *
  8251. * @type {Node<vec3>}
  8252. */
  8253. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8254. /**
  8255. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8256. *
  8257. * @type {Node<vec3>}
  8258. */
  8259. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8260. /**
  8261. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8262. *
  8263. * @type {Node<vec3>}
  8264. */
  8265. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8266. /**
  8267. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8268. *
  8269. * @type {Node<vec3>}
  8270. */
  8271. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8272. /**
  8273. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8274. *
  8275. * @type {Node<vec3>}
  8276. */
  8277. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8278. /** @module Bitangent **/
  8279. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8280. /**
  8281. * TSL object that represents the bitangent attribute of the current rendered object.
  8282. *
  8283. * @type {Node<vec3>}
  8284. */
  8285. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8286. /**
  8287. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8288. *
  8289. * @type {Node<vec3>}
  8290. */
  8291. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8292. /**
  8293. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8294. *
  8295. * @type {Node<vec4>}
  8296. */
  8297. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8298. /**
  8299. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8300. *
  8301. * @type {Node<vec4>}
  8302. */
  8303. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8304. /**
  8305. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8306. *
  8307. * @type {Node<vec4>}
  8308. */
  8309. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8310. /**
  8311. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8312. *
  8313. * @type {Node<vec4>}
  8314. */
  8315. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8316. /** @module AccessorsUtils **/
  8317. /**
  8318. * TSL object that represents the TBN matrix in view space.
  8319. *
  8320. * @type {Node<mat3>}
  8321. */
  8322. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8323. /**
  8324. * TSL object that represents the parallax direction.
  8325. *
  8326. * @type {Node<mat3>}
  8327. */
  8328. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8329. /**
  8330. * TSL function for computing parallax uv coordinates.
  8331. *
  8332. * @function
  8333. * @param {Node<vec2>} uv - A uv node.
  8334. * @param {Node<vec2>} scale - A scale node.
  8335. * @returns {Node<vec2>} Parallax uv coordinates.
  8336. */
  8337. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8338. /**
  8339. * TSL function for computing bent normals.
  8340. *
  8341. * @function
  8342. * @returns {Node<vec3>} Bent normals.
  8343. */
  8344. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8345. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8346. let bentNormal = anisotropyB.cross( positionViewDirection );
  8347. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8348. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8349. return bentNormal;
  8350. } )();
  8351. /** @module NormalMapNode **/
  8352. // Normal Mapping Without Precomputed Tangents
  8353. // http://www.thetenthplanet.de/archives/1180
  8354. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8355. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8356. const q0 = eye_pos.dFdx();
  8357. const q1 = eye_pos.dFdy();
  8358. const st0 = uv.dFdx();
  8359. const st1 = uv.dFdy();
  8360. const N = surf_norm; // normalized
  8361. const q1perp = q1.cross( N );
  8362. const q0perp = N.cross( q0 );
  8363. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8364. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8365. const det = T.dot( T ).max( B.dot( B ) );
  8366. const scale = faceDirection.mul( det.inverseSqrt() );
  8367. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8368. } );
  8369. /**
  8370. * This class can be used for applying normals maps to materials.
  8371. *
  8372. * ```js
  8373. * material.normalNode = normalMap( texture( normalTex ) );
  8374. * ```
  8375. *
  8376. * @augments TempNode
  8377. */
  8378. class NormalMapNode extends TempNode {
  8379. static get type() {
  8380. return 'NormalMapNode';
  8381. }
  8382. /**
  8383. * Constructs a new normal map node.
  8384. *
  8385. * @param {Node<vec3>} node - Represents the normal map data.
  8386. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8387. */
  8388. constructor( node, scaleNode = null ) {
  8389. super( 'vec3' );
  8390. /**
  8391. * Represents the normal map data.
  8392. *
  8393. * @type {Node<vec3>}
  8394. */
  8395. this.node = node;
  8396. /**
  8397. * Controls the intensity of the effect.
  8398. *
  8399. * @type {Node<vec2>?}
  8400. * @default null
  8401. */
  8402. this.scaleNode = scaleNode;
  8403. /**
  8404. * The normal map type.
  8405. *
  8406. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8407. * @default TangentSpaceNormalMap
  8408. */
  8409. this.normalMapType = TangentSpaceNormalMap;
  8410. }
  8411. setup( builder ) {
  8412. const { normalMapType, scaleNode } = this;
  8413. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8414. if ( scaleNode !== null ) {
  8415. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8416. }
  8417. let outputNode = null;
  8418. if ( normalMapType === ObjectSpaceNormalMap ) {
  8419. outputNode = transformNormalToView( normalMap );
  8420. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8421. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8422. if ( tangent === true ) {
  8423. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8424. } else {
  8425. outputNode = perturbNormal2Arb( {
  8426. eye_pos: positionView,
  8427. surf_norm: normalView,
  8428. mapN: normalMap,
  8429. uv: uv()
  8430. } );
  8431. }
  8432. }
  8433. return outputNode;
  8434. }
  8435. }
  8436. /**
  8437. * TSL function for creating a normal map node.
  8438. *
  8439. * @function
  8440. * @param {Node<vec3>} node - Represents the normal map data.
  8441. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8442. * @returns {NormalMapNode}
  8443. */
  8444. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8445. /** @module BumpMapNode **/
  8446. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8447. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8448. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8449. // It's used to preserve the same TextureNode instance
  8450. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8451. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8452. return vec2(
  8453. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8454. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8455. ).mul( bumpScale );
  8456. } );
  8457. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8458. const perturbNormalArb = Fn( ( inputs ) => {
  8459. const { surf_pos, surf_norm, dHdxy } = inputs;
  8460. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8461. const vSigmaX = surf_pos.dFdx().normalize();
  8462. const vSigmaY = surf_pos.dFdy().normalize();
  8463. const vN = surf_norm; // normalized
  8464. const R1 = vSigmaY.cross( vN );
  8465. const R2 = vN.cross( vSigmaX );
  8466. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8467. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8468. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8469. } );
  8470. /**
  8471. * This class can be used for applying bump maps to materials.
  8472. *
  8473. * ```js
  8474. * material.normalNode = bumpMap( texture( bumpTex ) );
  8475. * ```
  8476. *
  8477. * @augments TempNode
  8478. */
  8479. class BumpMapNode extends TempNode {
  8480. static get type() {
  8481. return 'BumpMapNode';
  8482. }
  8483. /**
  8484. * Constructs a new bump map node.
  8485. *
  8486. * @param {Node<float>} textureNode - Represents the bump map data.
  8487. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8488. */
  8489. constructor( textureNode, scaleNode = null ) {
  8490. super( 'vec3' );
  8491. /**
  8492. * Represents the bump map data.
  8493. *
  8494. * @type {Node<float>}
  8495. */
  8496. this.textureNode = textureNode;
  8497. /**
  8498. * Controls the intensity of the bump effect.
  8499. *
  8500. * @type {Node<float>?}
  8501. * @default null
  8502. */
  8503. this.scaleNode = scaleNode;
  8504. }
  8505. setup() {
  8506. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8507. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8508. return perturbNormalArb( {
  8509. surf_pos: positionView,
  8510. surf_norm: normalView,
  8511. dHdxy
  8512. } );
  8513. }
  8514. }
  8515. /**
  8516. * TSL function for creating a bump map node.
  8517. *
  8518. * @function
  8519. * @param {Node<float>} textureNode - Represents the bump map data.
  8520. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8521. * @returns {BumpMapNode}
  8522. */
  8523. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8524. /** @module MaterialNode **/
  8525. const _propertyCache = new Map();
  8526. /**
  8527. * This class should simplify the node access to material properties.
  8528. * It internal uses reference nodes to make sure changes to material
  8529. * properties are automatically reflected to predefined TSL objects
  8530. * like e.g. `materialColor`.
  8531. *
  8532. * @augments Node
  8533. */
  8534. class MaterialNode extends Node {
  8535. static get type() {
  8536. return 'MaterialNode';
  8537. }
  8538. /**
  8539. * Constructs a new material node.
  8540. *
  8541. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8542. */
  8543. constructor( scope ) {
  8544. super();
  8545. /**
  8546. * The scope defines what material property is referred by the node.
  8547. *
  8548. * @type {String}
  8549. */
  8550. this.scope = scope;
  8551. }
  8552. /**
  8553. * Returns a cached reference node for the given property and type.
  8554. *
  8555. * @param {String} property - The name of the material property.
  8556. * @param {String} type - The uniform type of the property.
  8557. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8558. */
  8559. getCache( property, type ) {
  8560. let node = _propertyCache.get( property );
  8561. if ( node === undefined ) {
  8562. node = materialReference( property, type );
  8563. _propertyCache.set( property, node );
  8564. }
  8565. return node;
  8566. }
  8567. /**
  8568. * Returns a float-typed material reference node for the given property name.
  8569. *
  8570. * @param {String} property - The name of the material property.
  8571. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8572. */
  8573. getFloat( property ) {
  8574. return this.getCache( property, 'float' );
  8575. }
  8576. /**
  8577. * Returns a color-typed material reference node for the given property name.
  8578. *
  8579. * @param {String} property - The name of the material property.
  8580. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8581. */
  8582. getColor( property ) {
  8583. return this.getCache( property, 'color' );
  8584. }
  8585. /**
  8586. * Returns a texture-typed material reference node for the given property name.
  8587. *
  8588. * @param {String} property - The name of the material property.
  8589. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8590. */
  8591. getTexture( property ) {
  8592. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8593. }
  8594. /**
  8595. * The node setup is done depending on the selected scope. Multiple material properties
  8596. * might be grouped into a single node composition if they logically belong together.
  8597. *
  8598. * @param {NodeBuilder} builder - The current node builder.
  8599. * @return {Node} The node representing the selected scope.
  8600. */
  8601. setup( builder ) {
  8602. const material = builder.context.material;
  8603. const scope = this.scope;
  8604. let node = null;
  8605. if ( scope === MaterialNode.COLOR ) {
  8606. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8607. if ( material.map && material.map.isTexture === true ) {
  8608. node = colorNode.mul( this.getTexture( 'map' ) );
  8609. } else {
  8610. node = colorNode;
  8611. }
  8612. } else if ( scope === MaterialNode.OPACITY ) {
  8613. const opacityNode = this.getFloat( scope );
  8614. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8615. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8616. } else {
  8617. node = opacityNode;
  8618. }
  8619. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8620. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8621. node = this.getTexture( 'specular' ).r;
  8622. } else {
  8623. node = float( 1 );
  8624. }
  8625. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8626. const specularIntensityNode = this.getFloat( scope );
  8627. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8628. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8629. } else {
  8630. node = specularIntensityNode;
  8631. }
  8632. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8633. const specularColorNode = this.getColor( scope );
  8634. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8635. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8636. } else {
  8637. node = specularColorNode;
  8638. }
  8639. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8640. const roughnessNode = this.getFloat( scope );
  8641. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8642. node = roughnessNode.mul( this.getTexture( scope ).g );
  8643. } else {
  8644. node = roughnessNode;
  8645. }
  8646. } else if ( scope === MaterialNode.METALNESS ) {
  8647. const metalnessNode = this.getFloat( scope );
  8648. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8649. node = metalnessNode.mul( this.getTexture( scope ).b );
  8650. } else {
  8651. node = metalnessNode;
  8652. }
  8653. } else if ( scope === MaterialNode.EMISSIVE ) {
  8654. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8655. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8656. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8657. node = emissiveNode.mul( this.getTexture( scope ) );
  8658. } else {
  8659. node = emissiveNode;
  8660. }
  8661. } else if ( scope === MaterialNode.NORMAL ) {
  8662. if ( material.normalMap ) {
  8663. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8664. node.normalMapType = material.normalMapType;
  8665. } else if ( material.bumpMap ) {
  8666. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8667. } else {
  8668. node = normalView;
  8669. }
  8670. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8671. const clearcoatNode = this.getFloat( scope );
  8672. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8673. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8674. } else {
  8675. node = clearcoatNode;
  8676. }
  8677. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8678. const clearcoatRoughnessNode = this.getFloat( scope );
  8679. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8680. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8681. } else {
  8682. node = clearcoatRoughnessNode;
  8683. }
  8684. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8685. if ( material.clearcoatNormalMap ) {
  8686. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8687. } else {
  8688. node = normalView;
  8689. }
  8690. } else if ( scope === MaterialNode.SHEEN ) {
  8691. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8692. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8693. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8694. } else {
  8695. node = sheenNode;
  8696. }
  8697. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8698. const sheenRoughnessNode = this.getFloat( scope );
  8699. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8700. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8701. } else {
  8702. node = sheenRoughnessNode;
  8703. }
  8704. node = node.clamp( 0.07, 1.0 );
  8705. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8706. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8707. const anisotropyPolar = this.getTexture( scope );
  8708. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8709. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8710. } else {
  8711. node = materialAnisotropyVector;
  8712. }
  8713. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8714. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8715. if ( material.iridescenceThicknessMap ) {
  8716. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8717. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8718. } else {
  8719. node = iridescenceThicknessMaximum;
  8720. }
  8721. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8722. const transmissionNode = this.getFloat( scope );
  8723. if ( material.transmissionMap ) {
  8724. node = transmissionNode.mul( this.getTexture( scope ).r );
  8725. } else {
  8726. node = transmissionNode;
  8727. }
  8728. } else if ( scope === MaterialNode.THICKNESS ) {
  8729. const thicknessNode = this.getFloat( scope );
  8730. if ( material.thicknessMap ) {
  8731. node = thicknessNode.mul( this.getTexture( scope ).g );
  8732. } else {
  8733. node = thicknessNode;
  8734. }
  8735. } else if ( scope === MaterialNode.IOR ) {
  8736. node = this.getFloat( scope );
  8737. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8738. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8739. } else if ( scope === MaterialNode.AO ) {
  8740. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8741. } else {
  8742. const outputType = this.getNodeType( builder );
  8743. node = this.getCache( scope, outputType );
  8744. }
  8745. return node;
  8746. }
  8747. }
  8748. MaterialNode.ALPHA_TEST = 'alphaTest';
  8749. MaterialNode.COLOR = 'color';
  8750. MaterialNode.OPACITY = 'opacity';
  8751. MaterialNode.SHININESS = 'shininess';
  8752. MaterialNode.SPECULAR = 'specular';
  8753. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8754. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8755. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8756. MaterialNode.REFLECTIVITY = 'reflectivity';
  8757. MaterialNode.ROUGHNESS = 'roughness';
  8758. MaterialNode.METALNESS = 'metalness';
  8759. MaterialNode.NORMAL = 'normal';
  8760. MaterialNode.CLEARCOAT = 'clearcoat';
  8761. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8762. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8763. MaterialNode.EMISSIVE = 'emissive';
  8764. MaterialNode.ROTATION = 'rotation';
  8765. MaterialNode.SHEEN = 'sheen';
  8766. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8767. MaterialNode.ANISOTROPY = 'anisotropy';
  8768. MaterialNode.IRIDESCENCE = 'iridescence';
  8769. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8770. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8771. MaterialNode.IOR = 'ior';
  8772. MaterialNode.TRANSMISSION = 'transmission';
  8773. MaterialNode.THICKNESS = 'thickness';
  8774. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8775. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8776. MaterialNode.LINE_SCALE = 'scale';
  8777. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8778. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8779. MaterialNode.LINE_WIDTH = 'linewidth';
  8780. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8781. MaterialNode.POINT_SIZE = 'size';
  8782. MaterialNode.DISPERSION = 'dispersion';
  8783. MaterialNode.LIGHT_MAP = 'light';
  8784. MaterialNode.AO = 'ao';
  8785. /**
  8786. * TSL object that represents alpha test of the current material.
  8787. *
  8788. * @type {Node<float>}
  8789. */
  8790. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8791. /**
  8792. * TSL object that represents the diffuse color of the current material.
  8793. * The value is composed via `color` * `map`.
  8794. *
  8795. * @type {Node<vec3>}
  8796. */
  8797. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8798. /**
  8799. * TSL object that represents the shininess of the current material.
  8800. *
  8801. * @type {Node<float>}
  8802. */
  8803. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8804. /**
  8805. * TSL object that represents the emissive color of the current material.
  8806. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8807. *
  8808. * @type {Node<vec3>}
  8809. */
  8810. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8811. /**
  8812. * TSL object that represents the opacity of the current material.
  8813. * The value is composed via `opacity` * `alphaMap`.
  8814. *
  8815. * @type {Node<float>}
  8816. */
  8817. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8818. /**
  8819. * TSL object that represents the specular of the current material.
  8820. *
  8821. * @type {Node<vec3>}
  8822. */
  8823. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8824. /**
  8825. * TSL object that represents the specular intensity of the current material.
  8826. * The value is composed via `specularIntensity` * `specularMap.a`.
  8827. *
  8828. * @type {Node<float>}
  8829. */
  8830. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8831. /**
  8832. * TSL object that represents the specular color of the current material.
  8833. * The value is composed via `specularColor` * `specularMap.rgb`.
  8834. *
  8835. * @type {Node<vec3>}
  8836. */
  8837. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8838. /**
  8839. * TSL object that represents the specular strength of the current material.
  8840. * The value is composed via `specularMap.r`.
  8841. *
  8842. * @type {Node<float>}
  8843. */
  8844. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8845. /**
  8846. * TSL object that represents the reflectivity of the current material.
  8847. *
  8848. * @type {Node<float>}
  8849. */
  8850. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8851. /**
  8852. * TSL object that represents the roughness of the current material.
  8853. * The value is composed via `roughness` * `roughnessMap.g`.
  8854. *
  8855. * @type {Node<float>}
  8856. */
  8857. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8858. /**
  8859. * TSL object that represents the metalness of the current material.
  8860. * The value is composed via `metalness` * `metalnessMap.b`.
  8861. *
  8862. * @type {Node<float>}
  8863. */
  8864. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8865. /**
  8866. * TSL object that represents the normal of the current material.
  8867. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8868. *
  8869. * @type {Node<vec3>}
  8870. */
  8871. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8872. /**
  8873. * TSL object that represents the clearcoat of the current material.
  8874. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8875. *
  8876. * @type {Node<float>}
  8877. */
  8878. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8879. /**
  8880. * TSL object that represents the clearcoat roughness of the current material.
  8881. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  8882. *
  8883. * @type {Node<float>}
  8884. */
  8885. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8886. /**
  8887. * TSL object that represents the clearcoat normal of the current material.
  8888. * The value will be either `clearcoatNormalMap` or `normalView`.
  8889. *
  8890. * @type {Node<vec3>}
  8891. */
  8892. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  8893. /**
  8894. * TSL object that represents the rotation of the current sprite material.
  8895. *
  8896. * @type {Node<float>}
  8897. */
  8898. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8899. /**
  8900. * TSL object that represents the sheen color of the current material.
  8901. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8902. *
  8903. * @type {Node<vec3>}
  8904. */
  8905. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8906. /**
  8907. * TSL object that represents the sheen roughness of the current material.
  8908. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  8909. *
  8910. * @type {Node<float>}
  8911. */
  8912. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8913. /**
  8914. * TSL object that represents the anisotropy of the current material.
  8915. *
  8916. * @type {Node<vec2>}
  8917. */
  8918. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8919. /**
  8920. * TSL object that represents the iridescence of the current material.
  8921. *
  8922. * @type {Node<float>}
  8923. */
  8924. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8925. /**
  8926. * TSL object that represents the iridescence IOR of the current material.
  8927. *
  8928. * @type {Node<float>}
  8929. */
  8930. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8931. /**
  8932. * TSL object that represents the iridescence thickness of the current material.
  8933. *
  8934. * @type {Node<float>}
  8935. */
  8936. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8937. /**
  8938. * TSL object that represents the transmission of the current material.
  8939. * The value is composed via `transmission` * `transmissionMap.r`.
  8940. *
  8941. * @type {Node<float>}
  8942. */
  8943. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8944. /**
  8945. * TSL object that represents the thickness of the current material.
  8946. * The value is composed via `thickness` * `thicknessMap.g`.
  8947. *
  8948. * @type {Node<float>}
  8949. */
  8950. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8951. /**
  8952. * TSL object that represents the IOR of the current material.
  8953. *
  8954. * @type {Node<float>}
  8955. */
  8956. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8957. /**
  8958. * TSL object that represents the attenuation distance of the current material.
  8959. *
  8960. * @type {Node<float>}
  8961. */
  8962. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8963. /**
  8964. * TSL object that represents the attenuation color of the current material.
  8965. *
  8966. * @type {Node<vec3>}
  8967. */
  8968. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8969. /**
  8970. * TSL object that represents the scale of the current dashed line material.
  8971. *
  8972. * @type {Node<float>}
  8973. */
  8974. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8975. /**
  8976. * TSL object that represents the dash size of the current dashed line material.
  8977. *
  8978. * @type {Node<float>}
  8979. */
  8980. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8981. /**
  8982. * TSL object that represents the gap size of the current dashed line material.
  8983. *
  8984. * @type {Node<float>}
  8985. */
  8986. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8987. /**
  8988. * TSL object that represents the line width of the current line material.
  8989. *
  8990. * @type {Node<float>}
  8991. */
  8992. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8993. /**
  8994. * TSL object that represents the dash offset of the current line material.
  8995. *
  8996. * @type {Node<float>}
  8997. */
  8998. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8999. /**
  9000. * TSL object that represents the point size of the current points material.
  9001. *
  9002. * @type {Node<float>}
  9003. */
  9004. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9005. /**
  9006. * TSL object that represents the dispersion of the current material.
  9007. *
  9008. * @type {Node<float>}
  9009. */
  9010. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9011. /**
  9012. * TSL object that represents the light map of the current material.
  9013. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9014. *
  9015. * @type {Node<vec3>}
  9016. */
  9017. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9018. /**
  9019. * TSL object that represents the ambient occlusion map of the current material.
  9020. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9021. *
  9022. * @type {Node<float>}
  9023. */
  9024. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9025. /**
  9026. * TSL object that represents the anisotropy vector of the current material.
  9027. *
  9028. * @type {Node<vec2>}
  9029. */
  9030. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9031. return frame.material;
  9032. } ).onRenderUpdate( function ( { material } ) {
  9033. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9034. } );
  9035. /** @module ModelViewProjectionNode **/
  9036. /**
  9037. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9038. *
  9039. * @type {VaryingNode<vec4>}
  9040. */
  9041. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9042. return builder.context.setupModelViewProjection();
  9043. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9044. /** @module IndexNode **/
  9045. /**
  9046. * This class represents shader indices of different types. The following predefined node
  9047. * objects cover frequent use cases:
  9048. *
  9049. * - `vertexIndex`: The index of a vertex within a mesh.
  9050. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9051. * - `drawIndex`: The index of a draw call.
  9052. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9053. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9054. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9055. *
  9056. * @augments Node
  9057. */
  9058. class IndexNode extends Node {
  9059. static get type() {
  9060. return 'IndexNode';
  9061. }
  9062. /**
  9063. * Constructs a new index node.
  9064. *
  9065. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9066. */
  9067. constructor( scope ) {
  9068. super( 'uint' );
  9069. /**
  9070. * The scope of the index node.
  9071. *
  9072. * @type {String}
  9073. */
  9074. this.scope = scope;
  9075. /**
  9076. * This flag can be used for type testing.
  9077. *
  9078. * @type {Boolean}
  9079. * @readonly
  9080. * @default true
  9081. */
  9082. this.isIndexNode = true;
  9083. }
  9084. generate( builder ) {
  9085. const nodeType = this.getNodeType( builder );
  9086. const scope = this.scope;
  9087. let propertyName;
  9088. if ( scope === IndexNode.VERTEX ) {
  9089. propertyName = builder.getVertexIndex();
  9090. } else if ( scope === IndexNode.INSTANCE ) {
  9091. propertyName = builder.getInstanceIndex();
  9092. } else if ( scope === IndexNode.DRAW ) {
  9093. propertyName = builder.getDrawIndex();
  9094. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9095. propertyName = builder.getInvocationLocalIndex();
  9096. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9097. propertyName = builder.getInvocationSubgroupIndex();
  9098. } else if ( scope === IndexNode.SUBGROUP ) {
  9099. propertyName = builder.getSubgroupIndex();
  9100. } else {
  9101. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9102. }
  9103. let output;
  9104. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9105. output = propertyName;
  9106. } else {
  9107. const nodeVarying = varying( this );
  9108. output = nodeVarying.build( builder, nodeType );
  9109. }
  9110. return output;
  9111. }
  9112. }
  9113. IndexNode.VERTEX = 'vertex';
  9114. IndexNode.INSTANCE = 'instance';
  9115. IndexNode.SUBGROUP = 'subgroup';
  9116. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9117. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9118. IndexNode.DRAW = 'draw';
  9119. /**
  9120. * TSL object that represents the index of a vertex within a mesh.
  9121. *
  9122. * @type {IndexNode}
  9123. */
  9124. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9125. /**
  9126. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9127. *
  9128. * @type {IndexNode}
  9129. */
  9130. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9131. /**
  9132. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9133. *
  9134. * @type {IndexNode}
  9135. */
  9136. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9137. /**
  9138. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9139. *
  9140. * @type {IndexNode}
  9141. */
  9142. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9143. /**
  9144. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9145. *
  9146. * @type {IndexNode}
  9147. */
  9148. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9149. /**
  9150. * TSL object that represents the index of a draw call.
  9151. *
  9152. * @type {IndexNode}
  9153. */
  9154. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9155. /** @module InstanceNode **/
  9156. /**
  9157. * This node implements the vertex shader logic which is required
  9158. * when rendering 3D objects via instancing. The code makes sure
  9159. * vertex positions, normals and colors can be modified via instanced
  9160. * data.
  9161. *
  9162. * @augments Node
  9163. */
  9164. class InstanceNode extends Node {
  9165. static get type() {
  9166. return 'InstanceNode';
  9167. }
  9168. /**
  9169. * Constructs a new instance node.
  9170. *
  9171. * @param {Number} count - The number of instances.
  9172. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9173. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9174. */
  9175. constructor( count, instanceMatrix, instanceColor ) {
  9176. super( 'void' );
  9177. /**
  9178. * The number of instances.
  9179. *
  9180. * @type {Number}
  9181. */
  9182. this.count = count;
  9183. /**
  9184. * Instanced buffer attribute representing the transformation of instances.
  9185. *
  9186. * @type {InstancedBufferAttribute}
  9187. */
  9188. this.instanceMatrix = instanceMatrix;
  9189. /**
  9190. * Instanced buffer attribute representing the color of instances.
  9191. *
  9192. * @type {InstancedBufferAttribute}
  9193. */
  9194. this.instanceColor = instanceColor;
  9195. /**
  9196. * The node that represents the instance matrix data.
  9197. *
  9198. * @type {Node}
  9199. */
  9200. this.instanceMatrixNode = null;
  9201. /**
  9202. * The node that represents the instance color data.
  9203. *
  9204. * @type {Node}
  9205. */
  9206. this.instanceColorNode = null;
  9207. /**
  9208. * The update type is set to `frame` since an update
  9209. * of instanced buffer data must be checked per frame.
  9210. *
  9211. * @type {String}
  9212. * @default 'frame'
  9213. */
  9214. this.updateType = NodeUpdateType.FRAME;
  9215. /**
  9216. * A reference to a buffer that is used by `instanceMatrixNode`.
  9217. *
  9218. * @type {InstancedInterleavedBuffer}
  9219. */
  9220. this.buffer = null;
  9221. /**
  9222. * A reference to a buffer that is used by `instanceColorNode`.
  9223. *
  9224. * @type {InstancedBufferAttribute}
  9225. */
  9226. this.bufferColor = null;
  9227. }
  9228. /**
  9229. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9230. * to predefined node variables for accumulation. That follows the same patterns
  9231. * like with morph and skinning nodes.
  9232. *
  9233. * @param {NodeBuilder} builder - The current node builder.
  9234. */
  9235. setup( builder ) {
  9236. const { count, instanceMatrix, instanceColor } = this;
  9237. let { instanceMatrixNode, instanceColorNode } = this;
  9238. if ( instanceMatrixNode === null ) {
  9239. // 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.
  9240. if ( count <= 1000 ) {
  9241. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9242. } else {
  9243. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9244. this.buffer = buffer;
  9245. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9246. const instanceBuffers = [
  9247. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9248. bufferFn( buffer, 'vec4', 16, 0 ),
  9249. bufferFn( buffer, 'vec4', 16, 4 ),
  9250. bufferFn( buffer, 'vec4', 16, 8 ),
  9251. bufferFn( buffer, 'vec4', 16, 12 )
  9252. ];
  9253. instanceMatrixNode = mat4( ...instanceBuffers );
  9254. }
  9255. this.instanceMatrixNode = instanceMatrixNode;
  9256. }
  9257. if ( instanceColor && instanceColorNode === null ) {
  9258. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9259. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9260. this.bufferColor = buffer;
  9261. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9262. this.instanceColorNode = instanceColorNode;
  9263. }
  9264. // POSITION
  9265. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9266. positionLocal.assign( instancePosition );
  9267. // NORMAL
  9268. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9269. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9270. // ASSIGNS
  9271. normalLocal.assign( instanceNormal );
  9272. }
  9273. // COLOR
  9274. if ( this.instanceColorNode !== null ) {
  9275. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9276. }
  9277. }
  9278. /**
  9279. * Checks if the internal buffers required an update.
  9280. *
  9281. * @param {NodeFrame} frame - The current node frame.
  9282. */
  9283. update( /*frame*/ ) {
  9284. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9285. this.buffer.version = this.instanceMatrix.version;
  9286. }
  9287. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9288. this.bufferColor.version = this.instanceColor.version;
  9289. }
  9290. }
  9291. }
  9292. /**
  9293. * TSL function for creating an instance node.
  9294. *
  9295. * @function
  9296. * @param {Number} count - The number of instances.
  9297. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9298. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9299. * @returns {InstanceNode}
  9300. */
  9301. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9302. /** @module InstancedMeshNode **/
  9303. /**
  9304. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9305. * It allows an easier setup of the instance node.
  9306. *
  9307. * @augments module:InstanceNode~InstanceNode
  9308. */
  9309. class InstancedMeshNode extends InstanceNode {
  9310. static get type() {
  9311. return 'InstancedMeshNode';
  9312. }
  9313. /**
  9314. * Constructs a new instanced mesh node.
  9315. *
  9316. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9317. */
  9318. constructor( instancedMesh ) {
  9319. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9320. super( count, instanceMatrix, instanceColor );
  9321. /**
  9322. * A reference to the instanced mesh.
  9323. *
  9324. * @type {InstancedMesh}
  9325. */
  9326. this.instancedMesh = instancedMesh;
  9327. }
  9328. }
  9329. /**
  9330. * TSL function for creating an instanced mesh node.
  9331. *
  9332. * @function
  9333. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9334. * @returns {InstancedMeshNode}
  9335. */
  9336. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9337. /** @module BatchNode **/
  9338. /**
  9339. * This node implements the vertex shader logic which is required
  9340. * when rendering 3D objects via batching. `BatchNode` must be used
  9341. * with instances of {@link BatchedMesh}.
  9342. *
  9343. * @augments Node
  9344. */
  9345. class BatchNode extends Node {
  9346. static get type() {
  9347. return 'BatchNode';
  9348. }
  9349. /**
  9350. * Constructs a new batch node.
  9351. *
  9352. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9353. */
  9354. constructor( batchMesh ) {
  9355. super( 'void' );
  9356. /**
  9357. * A reference to batched mesh.
  9358. *
  9359. * @type {BatchedMesh}
  9360. */
  9361. this.batchMesh = batchMesh;
  9362. /**
  9363. * The batching index node.
  9364. *
  9365. * @type {IndexNode?}
  9366. * @default null
  9367. */
  9368. this.batchingIdNode = null;
  9369. }
  9370. /**
  9371. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9372. * to predefined node variables for accumulation. That follows the same patterns
  9373. * like with morph and skinning nodes.
  9374. *
  9375. * @param {NodeBuilder} builder - The current node builder.
  9376. */
  9377. setup( builder ) {
  9378. if ( this.batchingIdNode === null ) {
  9379. if ( builder.getDrawIndex() === null ) {
  9380. this.batchingIdNode = instanceIndex;
  9381. } else {
  9382. this.batchingIdNode = drawIndex;
  9383. }
  9384. }
  9385. const getIndirectIndex = Fn( ( [ id ] ) => {
  9386. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9387. const x = int( id ).modInt( int( size ) );
  9388. const y = int( id ).div( int( size ) );
  9389. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9390. } ).setLayout( {
  9391. name: 'getIndirectIndex',
  9392. type: 'uint',
  9393. inputs: [
  9394. { name: 'id', type: 'int' }
  9395. ]
  9396. } );
  9397. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9398. const matricesTexture = this.batchMesh._matricesTexture;
  9399. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9400. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9401. const x = j.modInt( size );
  9402. const y = j.div( int( size ) );
  9403. const batchingMatrix = mat4(
  9404. textureLoad( matricesTexture, ivec2( x, y ) ),
  9405. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9406. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9407. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9408. );
  9409. const colorsTexture = this.batchMesh._colorsTexture;
  9410. if ( colorsTexture !== null ) {
  9411. const getBatchingColor = Fn( ( [ id ] ) => {
  9412. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9413. const j = id;
  9414. const x = j.modInt( size );
  9415. const y = j.div( size );
  9416. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9417. } ).setLayout( {
  9418. name: 'getBatchingColor',
  9419. type: 'vec3',
  9420. inputs: [
  9421. { name: 'id', type: 'int' }
  9422. ]
  9423. } );
  9424. const color = getBatchingColor( indirectId );
  9425. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9426. }
  9427. const bm = mat3( batchingMatrix );
  9428. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9429. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9430. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9431. normalLocal.assign( batchingNormal );
  9432. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9433. tangentLocal.mulAssign( bm );
  9434. }
  9435. }
  9436. }
  9437. /**
  9438. * TSL function for creating a batch node.
  9439. *
  9440. * @function
  9441. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9442. * @returns {BatchNode}
  9443. */
  9444. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9445. /** @module SkinningNode **/
  9446. const _frameId = new WeakMap();
  9447. /**
  9448. * This node implements the vertex transformation shader logic which is required
  9449. * for skinning/skeletal animation.
  9450. *
  9451. * @augments Node
  9452. */
  9453. class SkinningNode extends Node {
  9454. static get type() {
  9455. return 'SkinningNode';
  9456. }
  9457. /**
  9458. * Constructs a new skinning node.
  9459. *
  9460. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9461. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9462. */
  9463. constructor( skinnedMesh, useReference = false ) {
  9464. super( 'void' );
  9465. /**
  9466. * The skinned mesh.
  9467. *
  9468. * @type {SkinnedMesh}
  9469. */
  9470. this.skinnedMesh = skinnedMesh;
  9471. /**
  9472. * Whether to use reference nodes for internal skinned mesh related data or not.
  9473. * TODO: Explain the purpose of the property.
  9474. *
  9475. * @type {Boolean}
  9476. */
  9477. this.useReference = useReference;
  9478. /**
  9479. * The update type overwritten since skinning nodes are updated per object.
  9480. *
  9481. * @type {String}
  9482. */
  9483. this.updateType = NodeUpdateType.OBJECT;
  9484. //
  9485. /**
  9486. * The skin index attribute.
  9487. *
  9488. * @type {AttributeNode}
  9489. */
  9490. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9491. /**
  9492. * The skin weight attribute.
  9493. *
  9494. * @type {AttributeNode}
  9495. */
  9496. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9497. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9498. if ( useReference ) {
  9499. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9500. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9501. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9502. } else {
  9503. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9504. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9505. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9506. }
  9507. /**
  9508. * The bind matrix node.
  9509. *
  9510. * @type {Node<mat4>}
  9511. */
  9512. this.bindMatrixNode = bindMatrixNode;
  9513. /**
  9514. * The bind matrix inverse node.
  9515. *
  9516. * @type {Node<mat4>}
  9517. */
  9518. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9519. /**
  9520. * The bind matrices as a uniform buffer node.
  9521. *
  9522. * @type {Node}
  9523. */
  9524. this.boneMatricesNode = boneMatricesNode;
  9525. /**
  9526. * The previous bind matrices as a uniform buffer node.
  9527. * Required for computing motion vectors.
  9528. *
  9529. * @type {Node?}
  9530. * @default null
  9531. */
  9532. this.previousBoneMatricesNode = null;
  9533. }
  9534. /**
  9535. * Transforms the given vertex position via skinning.
  9536. *
  9537. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9538. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9539. * @return {Node<vec3>} The transformed vertex position.
  9540. */
  9541. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9542. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9543. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9544. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9545. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9546. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9547. // POSITION
  9548. const skinVertex = bindMatrixNode.mul( position );
  9549. const skinned = add(
  9550. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9551. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9552. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9553. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9554. );
  9555. return bindMatrixInverseNode.mul( skinned ).xyz;
  9556. }
  9557. /**
  9558. * Transforms the given vertex normal via skinning.
  9559. *
  9560. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9561. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9562. * @return {Node<vec3>} The transformed vertex normal.
  9563. */
  9564. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9565. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9566. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9567. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9568. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9569. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9570. // NORMAL
  9571. let skinMatrix = add(
  9572. skinWeightNode.x.mul( boneMatX ),
  9573. skinWeightNode.y.mul( boneMatY ),
  9574. skinWeightNode.z.mul( boneMatZ ),
  9575. skinWeightNode.w.mul( boneMatW )
  9576. );
  9577. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9578. return skinMatrix.transformDirection( normal ).xyz;
  9579. }
  9580. /**
  9581. * Transforms the given vertex normal via skinning.
  9582. *
  9583. * @param {NodeBuilder} builder - The current node builder.
  9584. * @return {Node<vec3>} The skinned position from the previous frame.
  9585. */
  9586. getPreviousSkinnedPosition( builder ) {
  9587. const skinnedMesh = builder.object;
  9588. if ( this.previousBoneMatricesNode === null ) {
  9589. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9590. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9591. }
  9592. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9593. }
  9594. /**
  9595. * Returns `true` if bone matrices from the previous frame are required.
  9596. *
  9597. * @param {NodeBuilder} builder - The current node builder.
  9598. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9599. */
  9600. needsPreviousBoneMatrices( builder ) {
  9601. const mrt = builder.renderer.getMRT();
  9602. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9603. }
  9604. /**
  9605. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9606. *
  9607. * @param {NodeBuilder} builder - The current node builder.
  9608. */
  9609. setup( builder ) {
  9610. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9611. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9612. }
  9613. const skinPosition = this.getSkinnedPosition();
  9614. positionLocal.assign( skinPosition );
  9615. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9616. const skinNormal = this.getSkinnedNormal();
  9617. normalLocal.assign( skinNormal );
  9618. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9619. tangentLocal.assign( skinNormal );
  9620. }
  9621. }
  9622. }
  9623. /**
  9624. * Generates the code snippet of the skinning node.
  9625. *
  9626. * @param {NodeBuilder} builder - The current node builder.
  9627. * @param {String} output - The current output.
  9628. * @return {String} The generated code snippet.
  9629. */
  9630. generate( builder, output ) {
  9631. if ( output !== 'void' ) {
  9632. return positionLocal.build( builder, output );
  9633. }
  9634. }
  9635. /**
  9636. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9637. *
  9638. * @param {NodeFrame} frame - The current node frame.
  9639. */
  9640. update( frame ) {
  9641. const object = this.useReference ? frame.object : this.skinnedMesh;
  9642. const skeleton = object.skeleton;
  9643. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9644. _frameId.set( skeleton, frame.frameId );
  9645. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9646. skeleton.update();
  9647. }
  9648. }
  9649. /**
  9650. * TSL function for creating a skinning node.
  9651. *
  9652. * @function
  9653. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9654. * @returns {SkinningNode}
  9655. */
  9656. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9657. /**
  9658. * TSL function for creating a skinning node with reference usage.
  9659. *
  9660. * @function
  9661. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9662. * @returns {SkinningNode}
  9663. */
  9664. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9665. /** @module LoopNode **/
  9666. /**
  9667. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9668. * ```js
  9669. * Loop( count, ( { i } ) => {
  9670. *
  9671. * } );
  9672. * ```
  9673. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9674. * ```js
  9675. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9676. *
  9677. * } );
  9678. *```
  9679. * Nested loops can be defined in a compacted form:
  9680. * ```js
  9681. * Loop( 10, 5, ( { i, j } ) => {
  9682. *
  9683. * } );
  9684. * ```
  9685. * Loops that should run backwards can be defined like so:
  9686. * ```js
  9687. * Loop( { start: 10 }, () => {} );
  9688. * ```
  9689. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9690. * @augments Node
  9691. */
  9692. class LoopNode extends Node {
  9693. static get type() {
  9694. return 'LoopNode';
  9695. }
  9696. /**
  9697. * Constructs a new loop node.
  9698. *
  9699. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9700. */
  9701. constructor( params = [] ) {
  9702. super();
  9703. this.params = params;
  9704. }
  9705. /**
  9706. * Returns a loop variable name based on an index. The pattern is
  9707. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9708. *
  9709. * @param {Number} index - The index.
  9710. * @return {String} The loop variable name.
  9711. */
  9712. getVarName( index ) {
  9713. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9714. }
  9715. /**
  9716. * Returns properties about this node.
  9717. *
  9718. * @param {NodeBuilder} builder - The current node builder.
  9719. * @return {Object} The node properties.
  9720. */
  9721. getProperties( builder ) {
  9722. const properties = builder.getNodeProperties( this );
  9723. if ( properties.stackNode !== undefined ) return properties;
  9724. //
  9725. const inputs = {};
  9726. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9727. const param = this.params[ i ];
  9728. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9729. const type = ( param.isNode !== true && param.type ) || 'int';
  9730. inputs[ name ] = expression( name, type );
  9731. }
  9732. const stack = builder.addStack(); // TODO: cache() it
  9733. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9734. properties.stackNode = stack;
  9735. builder.removeStack();
  9736. return properties;
  9737. }
  9738. /**
  9739. * This method is overwritten since the node type is inferred based on the loop configuration.
  9740. *
  9741. * @param {NodeBuilder} builder - The current node builder.
  9742. * @return {String} The node type.
  9743. */
  9744. getNodeType( builder ) {
  9745. const { returnsNode } = this.getProperties( builder );
  9746. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9747. }
  9748. setup( builder ) {
  9749. // setup properties
  9750. this.getProperties( builder );
  9751. }
  9752. generate( builder ) {
  9753. const properties = this.getProperties( builder );
  9754. const params = this.params;
  9755. const stackNode = properties.stackNode;
  9756. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9757. const param = params[ i ];
  9758. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9759. if ( param.isNode ) {
  9760. type = 'int';
  9761. name = this.getVarName( i );
  9762. start = '0';
  9763. end = param.build( builder, type );
  9764. condition = '<';
  9765. } else {
  9766. type = param.type || 'int';
  9767. name = param.name || this.getVarName( i );
  9768. start = param.start;
  9769. end = param.end;
  9770. condition = param.condition;
  9771. update = param.update;
  9772. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9773. else if ( start && start.isNode ) start = start.build( builder, type );
  9774. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9775. else if ( end && end.isNode ) end = end.build( builder, type );
  9776. if ( start !== undefined && end === undefined ) {
  9777. start = start + ' - 1';
  9778. end = '0';
  9779. condition = '>=';
  9780. } else if ( end !== undefined && start === undefined ) {
  9781. start = '0';
  9782. condition = '<';
  9783. }
  9784. if ( condition === undefined ) {
  9785. if ( Number( start ) > Number( end ) ) {
  9786. condition = '>=';
  9787. } else {
  9788. condition = '<';
  9789. }
  9790. }
  9791. }
  9792. const internalParam = { start, end, condition };
  9793. //
  9794. const startSnippet = internalParam.start;
  9795. const endSnippet = internalParam.end;
  9796. let declarationSnippet = '';
  9797. let conditionalSnippet = '';
  9798. let updateSnippet = '';
  9799. if ( ! update ) {
  9800. if ( type === 'int' || type === 'uint' ) {
  9801. if ( condition.includes( '<' ) ) update = '++';
  9802. else update = '--';
  9803. } else {
  9804. if ( condition.includes( '<' ) ) update = '+= 1.';
  9805. else update = '-= 1.';
  9806. }
  9807. }
  9808. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9809. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9810. updateSnippet += name + ' ' + update;
  9811. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9812. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9813. }
  9814. const stackSnippet = stackNode.build( builder, 'void' );
  9815. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9816. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9817. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9818. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9819. }
  9820. builder.addFlowTab();
  9821. return returnsSnippet;
  9822. }
  9823. }
  9824. /**
  9825. * TSL function for creating a loop node.
  9826. *
  9827. * @function
  9828. * @param {...Any} params - A list of parameters.
  9829. * @returns {LoopNode}
  9830. */
  9831. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9832. /**
  9833. * TSL function for creating a `Continue()` expression.
  9834. *
  9835. * @function
  9836. * @returns {ExpressionNode}
  9837. */
  9838. const Continue = () => expression( 'continue' ).append();
  9839. /**
  9840. * TSL function for creating a `Break()` expression.
  9841. *
  9842. * @function
  9843. * @returns {ExpressionNode}
  9844. */
  9845. const Break = () => expression( 'break' ).append();
  9846. // Deprecated
  9847. /**
  9848. * @function
  9849. * @deprecated since r168. Use {@link Loop} instead.
  9850. *
  9851. * @param {...any} params
  9852. * @returns {LoopNode}
  9853. */
  9854. const loop = ( ...params ) => { // @deprecated, r168
  9855. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9856. return Loop( ...params );
  9857. };
  9858. /** @module MorphNode **/
  9859. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9860. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9861. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9862. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9863. const y = texelIndex.div( width );
  9864. const x = texelIndex.sub( y.mul( width ) );
  9865. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9866. return bufferAttrib.mul( influence );
  9867. } );
  9868. function getEntry( geometry ) {
  9869. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9870. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9871. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9872. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9873. // into an array of data textures. Each layer represents a single morph target.
  9874. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9875. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9876. let entry = _morphTextures.get( geometry );
  9877. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9878. if ( entry !== undefined ) entry.texture.dispose();
  9879. const morphTargets = geometry.morphAttributes.position || [];
  9880. const morphNormals = geometry.morphAttributes.normal || [];
  9881. const morphColors = geometry.morphAttributes.color || [];
  9882. let vertexDataCount = 0;
  9883. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9884. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9885. if ( hasMorphColors === true ) vertexDataCount = 3;
  9886. let width = geometry.attributes.position.count * vertexDataCount;
  9887. let height = 1;
  9888. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9889. if ( width > maxTextureSize ) {
  9890. height = Math.ceil( width / maxTextureSize );
  9891. width = maxTextureSize;
  9892. }
  9893. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9894. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9895. bufferTexture.type = FloatType;
  9896. bufferTexture.needsUpdate = true;
  9897. // fill buffer
  9898. const vertexDataStride = vertexDataCount * 4;
  9899. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9900. const morphTarget = morphTargets[ i ];
  9901. const morphNormal = morphNormals[ i ];
  9902. const morphColor = morphColors[ i ];
  9903. const offset = width * height * 4 * i;
  9904. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9905. const stride = j * vertexDataStride;
  9906. if ( hasMorphPosition === true ) {
  9907. _morphVec4.fromBufferAttribute( morphTarget, j );
  9908. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9909. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9910. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9911. buffer[ offset + stride + 3 ] = 0;
  9912. }
  9913. if ( hasMorphNormals === true ) {
  9914. _morphVec4.fromBufferAttribute( morphNormal, j );
  9915. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9916. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9917. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9918. buffer[ offset + stride + 7 ] = 0;
  9919. }
  9920. if ( hasMorphColors === true ) {
  9921. _morphVec4.fromBufferAttribute( morphColor, j );
  9922. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9923. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9924. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9925. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9926. }
  9927. }
  9928. }
  9929. entry = {
  9930. count: morphTargetsCount,
  9931. texture: bufferTexture,
  9932. stride: vertexDataCount,
  9933. size: new Vector2( width, height )
  9934. };
  9935. _morphTextures.set( geometry, entry );
  9936. function disposeTexture() {
  9937. bufferTexture.dispose();
  9938. _morphTextures.delete( geometry );
  9939. geometry.removeEventListener( 'dispose', disposeTexture );
  9940. }
  9941. geometry.addEventListener( 'dispose', disposeTexture );
  9942. }
  9943. return entry;
  9944. }
  9945. /**
  9946. * This node implements the vertex transformation shader logic which is required
  9947. * for morph target animation.
  9948. *
  9949. * @augments Node
  9950. */
  9951. class MorphNode extends Node {
  9952. static get type() {
  9953. return 'MorphNode';
  9954. }
  9955. /**
  9956. * Constructs a new morph node.
  9957. *
  9958. * @param {Mesh} mesh - The mesh holding the morph targets.
  9959. */
  9960. constructor( mesh ) {
  9961. super( 'void' );
  9962. /**
  9963. * The mesh holding the morph targets.
  9964. *
  9965. * @type {Mesh}
  9966. */
  9967. this.mesh = mesh;
  9968. /**
  9969. * A uniform node which represents the morph base influence value.
  9970. *
  9971. * @type {UniformNode<float>}
  9972. */
  9973. this.morphBaseInfluence = uniform( 1 );
  9974. /**
  9975. * The update type overwritten since morph nodes are updated per object.
  9976. *
  9977. * @type {String}
  9978. */
  9979. this.updateType = NodeUpdateType.OBJECT;
  9980. }
  9981. /**
  9982. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9983. *
  9984. * @param {NodeBuilder} builder - The current node builder.
  9985. */
  9986. setup( builder ) {
  9987. const { geometry } = builder;
  9988. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9989. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9990. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9991. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9992. // nodes
  9993. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9994. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9995. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9996. const width = int( size.width );
  9997. Loop( morphTargetsCount, ( { i } ) => {
  9998. const influence = float( 0 ).toVar();
  9999. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10000. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10001. } else {
  10002. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10003. }
  10004. if ( hasMorphPosition === true ) {
  10005. positionLocal.addAssign( getMorph( {
  10006. bufferMap,
  10007. influence,
  10008. stride,
  10009. width,
  10010. depth: i,
  10011. offset: int( 0 )
  10012. } ) );
  10013. }
  10014. if ( hasMorphNormals === true ) {
  10015. normalLocal.addAssign( getMorph( {
  10016. bufferMap,
  10017. influence,
  10018. stride,
  10019. width,
  10020. depth: i,
  10021. offset: int( 1 )
  10022. } ) );
  10023. }
  10024. } );
  10025. }
  10026. /**
  10027. * Updates the state of the morphed mesh by updating the base influence.
  10028. *
  10029. * @param {NodeFrame} frame - The current node frame.
  10030. */
  10031. update( /*frame*/ ) {
  10032. const morphBaseInfluence = this.morphBaseInfluence;
  10033. if ( this.mesh.geometry.morphTargetsRelative ) {
  10034. morphBaseInfluence.value = 1;
  10035. } else {
  10036. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10037. }
  10038. }
  10039. }
  10040. /**
  10041. * TSL function for creating a morph node.
  10042. *
  10043. * @function
  10044. * @param {Mesh} mesh - The mesh holding the morph targets.
  10045. * @returns {MorphNode}
  10046. */
  10047. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10048. /**
  10049. * Base class for lighting nodes.
  10050. *
  10051. * @augments Node
  10052. */
  10053. class LightingNode extends Node {
  10054. static get type() {
  10055. return 'LightingNode';
  10056. }
  10057. /**
  10058. * Constructs a new lighting node.
  10059. */
  10060. constructor() {
  10061. super( 'vec3' );
  10062. /**
  10063. * This flag can be used for type testing.
  10064. *
  10065. * @type {Boolean}
  10066. * @readonly
  10067. * @default true
  10068. */
  10069. this.isLightingNode = true;
  10070. }
  10071. }
  10072. /**
  10073. * A generic class that can be used by nodes which contribute
  10074. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10075. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10076. *
  10077. * @augments LightingNode
  10078. */
  10079. class AONode extends LightingNode {
  10080. static get type() {
  10081. return 'AONode';
  10082. }
  10083. /**
  10084. * Constructs a new AO node.
  10085. *
  10086. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10087. */
  10088. constructor( aoNode = null ) {
  10089. super();
  10090. /**
  10091. * The ambient occlusion node.
  10092. *
  10093. * @type {Node<float>?}
  10094. * @default null
  10095. */
  10096. this.aoNode = aoNode;
  10097. }
  10098. setup( builder ) {
  10099. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10100. }
  10101. }
  10102. /**
  10103. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10104. * by adding lighting specific context data. It represents the runtime context of
  10105. * {@link LightsNode}.
  10106. *
  10107. * @augments ContextNode
  10108. */
  10109. class LightingContextNode extends ContextNode {
  10110. static get type() {
  10111. return 'LightingContextNode';
  10112. }
  10113. /**
  10114. * Constructs a new lighting context node.
  10115. *
  10116. * @param {LightsNode} node - The lights node.
  10117. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10118. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10119. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10120. */
  10121. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10122. super( node );
  10123. /**
  10124. * The current lighting model.
  10125. *
  10126. * @type {LightingModel?}
  10127. * @default null
  10128. */
  10129. this.lightingModel = lightingModel;
  10130. /**
  10131. * A backdrop node.
  10132. *
  10133. * @type {Node<vec3>?}
  10134. * @default null
  10135. */
  10136. this.backdropNode = backdropNode;
  10137. /**
  10138. * A backdrop alpha node.
  10139. *
  10140. * @type {Node<float>?}
  10141. * @default null
  10142. */
  10143. this.backdropAlphaNode = backdropAlphaNode;
  10144. this._value = null;
  10145. }
  10146. /**
  10147. * Returns a lighting context object.
  10148. *
  10149. * @return {{
  10150. * radiance: Node<vec3>,
  10151. * irradiance: Node<vec3>,
  10152. * iblIrradiance: Node<vec3>,
  10153. * ambientOcclusion: Node<float>,
  10154. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10155. * backdrop: Node<vec3>,
  10156. * backdropAlpha: Node<float>
  10157. * }} The lighting context object.
  10158. */
  10159. getContext() {
  10160. const { backdropNode, backdropAlphaNode } = this;
  10161. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10162. directSpecular = vec3().toVar( 'directSpecular' ),
  10163. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10164. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10165. const reflectedLight = {
  10166. directDiffuse,
  10167. directSpecular,
  10168. indirectDiffuse,
  10169. indirectSpecular
  10170. };
  10171. const context = {
  10172. radiance: vec3().toVar( 'radiance' ),
  10173. irradiance: vec3().toVar( 'irradiance' ),
  10174. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10175. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10176. reflectedLight,
  10177. backdrop: backdropNode,
  10178. backdropAlpha: backdropAlphaNode
  10179. };
  10180. return context;
  10181. }
  10182. setup( builder ) {
  10183. this.value = this._value || ( this._value = this.getContext() );
  10184. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10185. return super.setup( builder );
  10186. }
  10187. }
  10188. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10189. /**
  10190. * A generic class that can be used by nodes which contribute
  10191. * irradiance to the scene. E.g. a light map node can be used
  10192. * as input for this module. Used in {@link NodeMaterial}.
  10193. *
  10194. * @augments LightingNode
  10195. */
  10196. class IrradianceNode extends LightingNode {
  10197. static get type() {
  10198. return 'IrradianceNode';
  10199. }
  10200. /**
  10201. * Constructs a new irradiance node.
  10202. *
  10203. * @param {Node<vec3>} node - A node contributing irradiance.
  10204. */
  10205. constructor( node ) {
  10206. super();
  10207. /**
  10208. * A node contributing irradiance.
  10209. *
  10210. * @type {Node<vec3>}
  10211. */
  10212. this.node = node;
  10213. }
  10214. setup( builder ) {
  10215. builder.context.irradiance.addAssign( this.node );
  10216. }
  10217. }
  10218. /** @module ScreenNode **/
  10219. let screenSizeVec, viewportVec;
  10220. /**
  10221. * This node provides a collection of screen related metrics.
  10222. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10223. * resolution or viewport data as well as fragment or uv coordinates.
  10224. *
  10225. * @augments Node
  10226. */
  10227. class ScreenNode extends Node {
  10228. static get type() {
  10229. return 'ScreenNode';
  10230. }
  10231. /**
  10232. * Constructs a new screen node.
  10233. *
  10234. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10235. */
  10236. constructor( scope ) {
  10237. super();
  10238. /**
  10239. * The node represents different metric depending on which scope is selected.
  10240. *
  10241. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10242. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10243. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10244. * - `ScreenNode.UV`: Normalized coordinates.
  10245. *
  10246. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10247. */
  10248. this.scope = scope;
  10249. /**
  10250. * This flag can be used for type testing.
  10251. *
  10252. * @type {Boolean}
  10253. * @readonly
  10254. * @default true
  10255. */
  10256. this.isViewportNode = true;
  10257. }
  10258. /**
  10259. * This method is overwritten since the node type depends on the selected scope.
  10260. *
  10261. * @return {('vec2'|'vec4')} The node type.
  10262. */
  10263. getNodeType() {
  10264. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10265. else return 'vec2';
  10266. }
  10267. /**
  10268. * This method is overwritten since the node's update type depends on the selected scope.
  10269. *
  10270. * @return {NodeUpdateType} The update type.
  10271. */
  10272. getUpdateType() {
  10273. let updateType = NodeUpdateType.NONE;
  10274. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10275. updateType = NodeUpdateType.RENDER;
  10276. }
  10277. this.updateType = updateType;
  10278. return updateType;
  10279. }
  10280. /**
  10281. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10282. * from the current renderer.
  10283. *
  10284. * @param {NodeFrame} frame - A reference to the current node frame.
  10285. */
  10286. update( { renderer } ) {
  10287. const renderTarget = renderer.getRenderTarget();
  10288. if ( this.scope === ScreenNode.VIEWPORT ) {
  10289. if ( renderTarget !== null ) {
  10290. viewportVec.copy( renderTarget.viewport );
  10291. } else {
  10292. renderer.getViewport( viewportVec );
  10293. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10294. }
  10295. } else {
  10296. if ( renderTarget !== null ) {
  10297. screenSizeVec.width = renderTarget.width;
  10298. screenSizeVec.height = renderTarget.height;
  10299. } else {
  10300. renderer.getDrawingBufferSize( screenSizeVec );
  10301. }
  10302. }
  10303. }
  10304. setup( /*builder*/ ) {
  10305. const scope = this.scope;
  10306. let output = null;
  10307. if ( scope === ScreenNode.SIZE ) {
  10308. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10309. } else if ( scope === ScreenNode.VIEWPORT ) {
  10310. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10311. } else {
  10312. output = vec2( screenCoordinate.div( screenSize ) );
  10313. }
  10314. return output;
  10315. }
  10316. generate( builder ) {
  10317. if ( this.scope === ScreenNode.COORDINATE ) {
  10318. let coord = builder.getFragCoord();
  10319. if ( builder.isFlipY() ) {
  10320. // follow webgpu standards
  10321. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10322. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10323. }
  10324. return coord;
  10325. }
  10326. return super.generate( builder );
  10327. }
  10328. }
  10329. ScreenNode.COORDINATE = 'coordinate';
  10330. ScreenNode.VIEWPORT = 'viewport';
  10331. ScreenNode.SIZE = 'size';
  10332. ScreenNode.UV = 'uv';
  10333. // Screen
  10334. /**
  10335. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10336. *
  10337. * @type {ScreenNode<vec2>}
  10338. */
  10339. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10340. /**
  10341. * TSL object that represents the screen resolution in physical pixel units.
  10342. *
  10343. * @type {ScreenNode<vec2>}
  10344. */
  10345. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10346. /**
  10347. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10348. *
  10349. * @type {ScreenNode<vec2>}
  10350. */
  10351. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10352. // Viewport
  10353. /**
  10354. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10355. *
  10356. * @type {ScreenNode<vec4>}
  10357. */
  10358. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10359. /**
  10360. * TSL object that represents the viewport resolution in physical pixel units.
  10361. *
  10362. * @type {ScreenNode<vec2>}
  10363. */
  10364. const viewportSize = viewport.zw;
  10365. /**
  10366. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10367. *
  10368. * @type {ScreenNode<vec2>}
  10369. */
  10370. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10371. /**
  10372. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10373. *
  10374. * @type {ScreenNode<vec2>}
  10375. */
  10376. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10377. // Deprecated
  10378. /**
  10379. * @deprecated since r169. Use {@link screenSize} instead.
  10380. */
  10381. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10382. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10383. return screenSize;
  10384. }, 'vec2' ).once() )();
  10385. /**
  10386. * @deprecated since r168. Use {@link screenUV} instead.
  10387. */
  10388. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10389. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10390. return screenUV;
  10391. }, 'vec2' ).once() )();
  10392. /**
  10393. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10394. */
  10395. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10396. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10397. return screenUV.flipY();
  10398. }, 'vec2' ).once() )();
  10399. /** @module ViewportTextureNode **/
  10400. const _size$4 = /*@__PURE__*/ new Vector2();
  10401. /**
  10402. * A special type of texture node which represents the data of the current viewport
  10403. * as a texture. The module extracts data from the current bound framebuffer with
  10404. * a copy operation so no extra render pass is required to produce the texture data
  10405. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10406. * variety of effects like refractive or transmissive materials.
  10407. *
  10408. * @augments module:TextureNode~TextureNode
  10409. */
  10410. class ViewportTextureNode extends TextureNode {
  10411. static get type() {
  10412. return 'ViewportTextureNode';
  10413. }
  10414. /**
  10415. * Constructs a new viewport texture node.
  10416. *
  10417. * @param {Node} [uvNode=screenUV] - The uv node.
  10418. * @param {Node?} [levelNode=null] - The level node.
  10419. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10420. */
  10421. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10422. if ( framebufferTexture === null ) {
  10423. framebufferTexture = new FramebufferTexture();
  10424. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10425. }
  10426. super( framebufferTexture, uvNode, levelNode );
  10427. /**
  10428. * Whether to generate mipmaps or not.
  10429. *
  10430. * @type {Boolean}
  10431. * @default false
  10432. */
  10433. this.generateMipmaps = false;
  10434. /**
  10435. * This flag can be used for type testing.
  10436. *
  10437. * @type {Boolean}
  10438. * @readonly
  10439. * @default true
  10440. */
  10441. this.isOutputTextureNode = true;
  10442. /**
  10443. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10444. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10445. *
  10446. * @type {String}
  10447. * @default 'frame'
  10448. */
  10449. this.updateBeforeType = NodeUpdateType.FRAME;
  10450. }
  10451. updateBefore( frame ) {
  10452. const renderer = frame.renderer;
  10453. renderer.getDrawingBufferSize( _size$4 );
  10454. //
  10455. const framebufferTexture = this.value;
  10456. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10457. framebufferTexture.image.width = _size$4.width;
  10458. framebufferTexture.image.height = _size$4.height;
  10459. framebufferTexture.needsUpdate = true;
  10460. }
  10461. //
  10462. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10463. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10464. renderer.copyFramebufferToTexture( framebufferTexture );
  10465. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10466. }
  10467. clone() {
  10468. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10469. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10470. return viewportTextureNode;
  10471. }
  10472. }
  10473. /**
  10474. * TSL function for creating a viewport texture node.
  10475. *
  10476. * @function
  10477. * @param {Node} [uvNode=screenUV] - The uv node.
  10478. * @param {Node?} [levelNode=null] - The level node.
  10479. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10480. * @returns {ViewportTextureNode}
  10481. */
  10482. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10483. /**
  10484. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10485. *
  10486. * @function
  10487. * @param {Node} [uvNode=screenUV] - The uv node.
  10488. * @param {Node?} [levelNode=null] - The level node.
  10489. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10490. * @returns {ViewportTextureNode}
  10491. */
  10492. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10493. /** @module ViewportDepthTextureNode **/
  10494. let sharedDepthbuffer = null;
  10495. /**
  10496. * Represents the depth of the current viewport as a texture. This module
  10497. * can be used in combination with viewport texture to achieve effects
  10498. * that require depth evaluation.
  10499. *
  10500. * @augments module:ViewportTextureNode~ViewportTextureNode
  10501. */
  10502. class ViewportDepthTextureNode extends ViewportTextureNode {
  10503. static get type() {
  10504. return 'ViewportDepthTextureNode';
  10505. }
  10506. /**
  10507. * Constructs a new viewport depth texture node.
  10508. *
  10509. * @param {Node} [uvNode=screenUV] - The uv node.
  10510. * @param {Node?} [levelNode=null] - The level node.
  10511. */
  10512. constructor( uvNode = screenUV, levelNode = null ) {
  10513. if ( sharedDepthbuffer === null ) {
  10514. sharedDepthbuffer = new DepthTexture();
  10515. }
  10516. super( uvNode, levelNode, sharedDepthbuffer );
  10517. }
  10518. }
  10519. /**
  10520. * TSL function for a viewport depth texture node.
  10521. *
  10522. * @function
  10523. * @param {Node} [uvNode=screenUV] - The uv node.
  10524. * @param {Node?} [levelNode=null] - The level node.
  10525. * @returns {ViewportDepthTextureNode}
  10526. */
  10527. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10528. /** @module ViewportDepthNode **/
  10529. /**
  10530. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10531. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10532. * fragment or for depth evaluation purposes.
  10533. *
  10534. * @augments Node
  10535. */
  10536. class ViewportDepthNode extends Node {
  10537. static get type() {
  10538. return 'ViewportDepthNode';
  10539. }
  10540. /**
  10541. * Constructs a new viewport depth node.
  10542. *
  10543. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10544. * @param {Node?} [valueNode=null] - The value node.
  10545. */
  10546. constructor( scope, valueNode = null ) {
  10547. super( 'float' );
  10548. /**
  10549. * The node behaves differently depending on which scope is selected.
  10550. *
  10551. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10552. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10553. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10554. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10555. *
  10556. * @type {('depth'|'depthBase'|'linearDepth')}
  10557. */
  10558. this.scope = scope;
  10559. /**
  10560. * Can be used to define a custom depth value.
  10561. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10562. *
  10563. * @type {Node?}
  10564. * @default null
  10565. */
  10566. this.valueNode = valueNode;
  10567. /**
  10568. * This flag can be used for type testing.
  10569. *
  10570. * @type {Boolean}
  10571. * @readonly
  10572. * @default true
  10573. */
  10574. this.isViewportDepthNode = true;
  10575. }
  10576. generate( builder ) {
  10577. const { scope } = this;
  10578. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10579. return builder.getFragDepth();
  10580. }
  10581. return super.generate( builder );
  10582. }
  10583. setup( { camera } ) {
  10584. const { scope } = this;
  10585. const value = this.valueNode;
  10586. let node = null;
  10587. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10588. if ( value !== null ) {
  10589. node = depthBase().assign( value );
  10590. }
  10591. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10592. if ( camera.isPerspectiveCamera ) {
  10593. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10594. } else {
  10595. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10596. }
  10597. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10598. if ( value !== null ) {
  10599. if ( camera.isPerspectiveCamera ) {
  10600. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10601. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10602. } else {
  10603. node = value;
  10604. }
  10605. } else {
  10606. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10607. }
  10608. }
  10609. return node;
  10610. }
  10611. }
  10612. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10613. ViewportDepthNode.DEPTH = 'depth';
  10614. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10615. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10616. /**
  10617. * TSL function for converting a viewZ value to an orthographic depth value.
  10618. *
  10619. * @function
  10620. * @param {Node<float>} viewZ - The viewZ node.
  10621. * @param {Node<float>} near - The camera's near value.
  10622. * @param {Node<float>} far - The camera's far value.
  10623. * @returns {Node<float>}
  10624. */
  10625. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10626. /**
  10627. * TSL function for converting an orthographic depth value to a viewZ value.
  10628. *
  10629. * @function
  10630. * @param {Node<float>} depth - The orthographic depth.
  10631. * @param {Node<float>} near - The camera's near value.
  10632. * @param {Node<float>} far - The camera's far value.
  10633. * @returns {Node<float>}
  10634. */
  10635. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10636. /**
  10637. * TSL function for converting a viewZ value to a perspective depth value.
  10638. *
  10639. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10640. *
  10641. * @function
  10642. * @param {Node<float>} viewZ - The viewZ node.
  10643. * @param {Node<float>} near - The camera's near value.
  10644. * @param {Node<float>} far - The camera's far value.
  10645. * @returns {Node<float>}
  10646. */
  10647. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10648. /**
  10649. * TSL function for converting a perspective depth value to a viewZ value.
  10650. *
  10651. * @function
  10652. * @param {Node<float>} depth - The perspective depth.
  10653. * @param {Node<float>} near - The camera's near value.
  10654. * @param {Node<float>} far - The camera's far value.
  10655. * @returns {Node<float>}
  10656. */
  10657. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10658. /**
  10659. * TSL function for converting a viewZ value to a logarithmic depth value.
  10660. *
  10661. * @function
  10662. * @param {Node<float>} viewZ - The viewZ node.
  10663. * @param {Node<float>} near - The camera's near value.
  10664. * @param {Node<float>} far - The camera's far value.
  10665. * @returns {Node<float>}
  10666. */
  10667. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10668. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10669. // The final logarithmic depth formula used here is adapted from one described in an
  10670. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10671. // which was an improvement upon an earlier formula one described in an
  10672. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10673. // Ulrich's formula is the following:
  10674. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10675. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10676. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10677. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10678. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10679. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10680. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10681. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10682. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10683. // Outerra eventually made another improvement to their original "C-constant" variant,
  10684. // but it still does not incorporate the camera near plane (for this version,
  10685. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10686. // Here we make 4 changes to Ulrich's formula:
  10687. // 1. Clamp the camera near plane so we don't divide by 0.
  10688. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10689. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10690. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10691. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10692. // so we do the same here, hence the 'viewZ.negate()' call.
  10693. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10694. near = near.max( 1e-6 ).toVar();
  10695. const numerator = log2( viewZ.negate().div( near ) );
  10696. const denominator = log2( far.div( near ) );
  10697. return numerator.div( denominator );
  10698. };
  10699. /**
  10700. * TSL function for converting a logarithmic depth value to a viewZ value.
  10701. *
  10702. * @function
  10703. * @param {Node<float>} depth - The logarithmic depth.
  10704. * @param {Node<float>} near - The camera's near value.
  10705. * @param {Node<float>} far - The camera's far value.
  10706. * @returns {Node<float>}
  10707. */
  10708. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10709. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10710. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10711. // a negative viewZ).
  10712. const exponent = depth.mul( log( far.div( near ) ) );
  10713. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10714. };
  10715. /**
  10716. * TSL function for defining a value for the current fragment's depth.
  10717. *
  10718. * @function
  10719. * @param {Node<float>} value - The depth value to set.
  10720. * @returns {ViewportDepthNode<float>}
  10721. */
  10722. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10723. /**
  10724. * TSL object that represents the depth value for the current fragment.
  10725. *
  10726. * @type {ViewportDepthNode}
  10727. */
  10728. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10729. /**
  10730. * TSL function for converting a perspective depth value to linear depth.
  10731. *
  10732. * @function
  10733. * @param {Node<float>} value - The perspective depth.
  10734. * @returns {ViewportDepthNode<float>}
  10735. */
  10736. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10737. /**
  10738. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10739. *
  10740. * @type {ViewportDepthNode}
  10741. */
  10742. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10743. depth.assign = ( value ) => depthBase( value );
  10744. /** @module BuiltinNode **/
  10745. /**
  10746. * The node allows to set values for built-in shader variables. That is
  10747. * required for features like hardware-accelerated vertex clipping.
  10748. *
  10749. * @augments Node
  10750. */
  10751. class BuiltinNode extends Node {
  10752. /**
  10753. * Constructs a new builtin node.
  10754. *
  10755. * @param {String} name - The name of the built-in shader variable.
  10756. */
  10757. constructor( name ) {
  10758. super( 'float' );
  10759. /**
  10760. * The name of the built-in shader variable.
  10761. *
  10762. * @type {String}
  10763. */
  10764. this.name = name;
  10765. /**
  10766. * This flag can be used for type testing.
  10767. *
  10768. * @type {Boolean}
  10769. * @readonly
  10770. * @default true
  10771. */
  10772. this.isBuiltinNode = true;
  10773. }
  10774. /**
  10775. * Generates the code snippet of the builtin node.
  10776. *
  10777. * @param {NodeBuilder} builder - The current node builder.
  10778. * @return {String} The generated code snippet.
  10779. */
  10780. generate( /* builder */ ) {
  10781. return this.name;
  10782. }
  10783. }
  10784. /**
  10785. * TSL function for creating a builtin node.
  10786. *
  10787. * @function
  10788. * @param {String} name - The name of the built-in shader variable.
  10789. * @returns {BuiltinNode}
  10790. */
  10791. const builtin = nodeProxy( BuiltinNode );
  10792. /** @module ClippingNode **/
  10793. /**
  10794. * ```
  10795. * This node is used in {@link NodeMaterial} to setup the clipping
  10796. * which can happen hardware-accelerated (if supported) and optionally
  10797. * use alpha-to-coverage for anti-aliasing clipped edges.
  10798. * ```
  10799. * @augments Node
  10800. */
  10801. class ClippingNode extends Node {
  10802. static get type() {
  10803. return 'ClippingNode';
  10804. }
  10805. /**
  10806. * Constructs a new clipping node.
  10807. *
  10808. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10809. * the selected scope influences the behavior of the node and what type of code is generated.
  10810. */
  10811. constructor( scope = ClippingNode.DEFAULT ) {
  10812. super();
  10813. /**
  10814. * The node's scope. Similar to other nodes, the selected scope influences
  10815. * the behavior of the node and what type of code is generated.
  10816. *
  10817. * @type {('default'|'hardware'|'alphaToCoverage')}
  10818. */
  10819. this.scope = scope;
  10820. }
  10821. /**
  10822. * Setups the node depending on the selected scope.
  10823. *
  10824. * @param {NodeBuilder} builder - The current node builder.
  10825. * @return {Node} The result node.
  10826. */
  10827. setup( builder ) {
  10828. super.setup( builder );
  10829. const clippingContext = builder.clippingContext;
  10830. const { intersectionPlanes, unionPlanes } = clippingContext;
  10831. this.hardwareClipping = builder.material.hardwareClipping;
  10832. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10833. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10834. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10835. return this.setupHardwareClipping( unionPlanes, builder );
  10836. } else {
  10837. return this.setupDefault( intersectionPlanes, unionPlanes );
  10838. }
  10839. }
  10840. /**
  10841. * Setups alpha to coverage.
  10842. *
  10843. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10844. * @param {Array<Vector4>} unionPlanes - The union planes.
  10845. * @return {Node} The result node.
  10846. */
  10847. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10848. return Fn( () => {
  10849. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10850. const distanceGradient = float().toVar( 'distanceToGradient' );
  10851. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10852. const numUnionPlanes = unionPlanes.length;
  10853. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10854. const clippingPlanes = uniformArray( unionPlanes );
  10855. Loop( numUnionPlanes, ( { i } ) => {
  10856. const plane = clippingPlanes.element( i );
  10857. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10858. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10859. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10860. } );
  10861. }
  10862. const numIntersectionPlanes = intersectionPlanes.length;
  10863. if ( numIntersectionPlanes > 0 ) {
  10864. const clippingPlanes = uniformArray( intersectionPlanes );
  10865. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10866. Loop( numIntersectionPlanes, ( { i } ) => {
  10867. const plane = clippingPlanes.element( i );
  10868. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10869. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10870. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10871. } );
  10872. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10873. }
  10874. diffuseColor.a.mulAssign( clipOpacity );
  10875. diffuseColor.a.equal( 0.0 ).discard();
  10876. } )();
  10877. }
  10878. /**
  10879. * Setups the default clipping.
  10880. *
  10881. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10882. * @param {Array<Vector4>} unionPlanes - The union planes.
  10883. * @return {Node} The result node.
  10884. */
  10885. setupDefault( intersectionPlanes, unionPlanes ) {
  10886. return Fn( () => {
  10887. const numUnionPlanes = unionPlanes.length;
  10888. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10889. const clippingPlanes = uniformArray( unionPlanes );
  10890. Loop( numUnionPlanes, ( { i } ) => {
  10891. const plane = clippingPlanes.element( i );
  10892. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10893. } );
  10894. }
  10895. const numIntersectionPlanes = intersectionPlanes.length;
  10896. if ( numIntersectionPlanes > 0 ) {
  10897. const clippingPlanes = uniformArray( intersectionPlanes );
  10898. const clipped = bool( true ).toVar( 'clipped' );
  10899. Loop( numIntersectionPlanes, ( { i } ) => {
  10900. const plane = clippingPlanes.element( i );
  10901. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10902. } );
  10903. clipped.discard();
  10904. }
  10905. } )();
  10906. }
  10907. /**
  10908. * Setups hardware clipping.
  10909. *
  10910. * @param {Array<Vector4>} unionPlanes - The union planes.
  10911. * @param {NodeBuilder} builder - The current node builder.
  10912. * @return {Node} The result node.
  10913. */
  10914. setupHardwareClipping( unionPlanes, builder ) {
  10915. const numUnionPlanes = unionPlanes.length;
  10916. builder.enableHardwareClipping( numUnionPlanes );
  10917. return Fn( () => {
  10918. const clippingPlanes = uniformArray( unionPlanes );
  10919. const hw_clip_distances = builtin( builder.getClipDistance() );
  10920. Loop( numUnionPlanes, ( { i } ) => {
  10921. const plane = clippingPlanes.element( i );
  10922. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10923. hw_clip_distances.element( i ).assign( distance );
  10924. } );
  10925. } )();
  10926. }
  10927. }
  10928. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10929. ClippingNode.DEFAULT = 'default';
  10930. ClippingNode.HARDWARE = 'hardware';
  10931. /**
  10932. * TSL function for setting up the default clipping logic.
  10933. *
  10934. * @function
  10935. * @returns {ClippingNode}
  10936. */
  10937. const clipping = () => nodeObject( new ClippingNode() );
  10938. /**
  10939. * TSL function for setting up alpha to coverage.
  10940. *
  10941. * @function
  10942. * @returns {ClippingNode}
  10943. */
  10944. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10945. /**
  10946. * TSL function for setting up hardware-based clipping.
  10947. *
  10948. * @function
  10949. * @returns {ClippingNode}
  10950. */
  10951. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10952. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10953. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10954. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10955. 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 ) ) ) ) ) );
  10956. } );
  10957. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10958. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10959. } );
  10960. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10961. // Find the discretized derivatives of our coordinates
  10962. const maxDeriv = max$1(
  10963. length( dFdx( position.xyz ) ),
  10964. length( dFdy( position.xyz ) )
  10965. );
  10966. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10967. // Find two nearest log-discretized noise scales
  10968. const pixScales = vec2(
  10969. exp2( floor( log2( pixScale ) ) ),
  10970. exp2( ceil( log2( pixScale ) ) )
  10971. );
  10972. // Compute alpha thresholds at our two noise scales
  10973. const alpha = vec2(
  10974. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10975. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10976. );
  10977. // Factor to interpolate lerp with
  10978. const lerpFactor = fract( log2( pixScale ) );
  10979. // Interpolate alpha threshold from noise at two scales
  10980. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10981. // Pass into CDF to compute uniformly distrib threshold
  10982. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10983. const cases = vec3(
  10984. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10985. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10986. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10987. // Find our final, uniformly distributed alpha threshold (ατ)
  10988. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10989. // Avoids ατ == 0. Could also do ατ =1-ατ
  10990. return clamp( threshold, 1.0e-6, 1.0 );
  10991. } ).setLayout( {
  10992. name: 'getAlphaHashThreshold',
  10993. type: 'float',
  10994. inputs: [
  10995. { name: 'position', type: 'vec3' }
  10996. ]
  10997. } );
  10998. /**
  10999. * Base class for all node materials.
  11000. *
  11001. * @augments Material
  11002. */
  11003. class NodeMaterial extends Material {
  11004. static get type() {
  11005. return 'NodeMaterial';
  11006. }
  11007. /**
  11008. * Represents the type of the node material.
  11009. *
  11010. * @type {String}
  11011. */
  11012. get type() {
  11013. return this.constructor.type;
  11014. }
  11015. set type( _value ) { /* */ }
  11016. /**
  11017. * Constructs a new node material.
  11018. */
  11019. constructor() {
  11020. super();
  11021. /**
  11022. * This flag can be used for type testing.
  11023. *
  11024. * @type {Boolean}
  11025. * @readonly
  11026. * @default true
  11027. */
  11028. this.isNodeMaterial = true;
  11029. /**
  11030. * Whether this material is affected by fog or not.
  11031. *
  11032. * @type {Boolean}
  11033. * @default true
  11034. */
  11035. this.fog = true;
  11036. /**
  11037. * Whether this material is affected by lights or not.
  11038. *
  11039. * @type {Boolean}
  11040. * @default false
  11041. */
  11042. this.lights = false;
  11043. /**
  11044. * Whether this material uses hardware clipping or not.
  11045. * This property is managed by the engine and should not be
  11046. * modified by apps.
  11047. *
  11048. * @type {Boolean}
  11049. * @default false
  11050. */
  11051. this.hardwareClipping = false;
  11052. /**
  11053. * Node materials which set their `lights` property to `true`
  11054. * are affected by all lights of the scene. Sometimes selective
  11055. * lighting is wanted which means only _some_ lights in the scene
  11056. * affect a material. This can be achieved by creating an instance
  11057. * of {@link module:LightsNode~LightsNode} with a list of selective
  11058. * lights and assign the node to this property.
  11059. *
  11060. * ```js
  11061. * const customLightsNode = lights( [ light1, light2 ] );
  11062. * material.lightsNode = customLightsNode;
  11063. * ```
  11064. *
  11065. * @type {LightsNode?}
  11066. * @default null
  11067. */
  11068. this.lightsNode = null;
  11069. /**
  11070. * The environment of node materials can be defined by an environment
  11071. * map assigned to the `envMap` property or by `Scene.environment`
  11072. * if the node material is a PBR material. This node property allows to overwrite
  11073. * the default behavior and define the environment with a custom node.
  11074. *
  11075. * ```js
  11076. * material.envNode = pmremTexture( renderTarget.texture );
  11077. * ```
  11078. *
  11079. * @type {Node<vec3>?}
  11080. * @default null
  11081. */
  11082. this.envNode = null;
  11083. /**
  11084. * The lighting of node materials might be influenced by ambient occlusion.
  11085. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11086. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11087. * the default and define the ambient occlusion with a custom node instead.
  11088. *
  11089. * If you don't want to overwrite the diffuse color but modify the existing
  11090. * values instead, use {@link module:MaterialNode.materialAO}.
  11091. *
  11092. * @type {Node<float>?}
  11093. * @default null
  11094. */
  11095. this.aoNode = null;
  11096. /**
  11097. * The diffuse color of node materials is by default inferred from the
  11098. * `color` and `map` properties. This node property allows to overwrite the default
  11099. * and define the diffuse color with a node instead.
  11100. *
  11101. * ```js
  11102. * material.colorNode = color( 0xff0000 ); // define red color
  11103. * ```
  11104. *
  11105. * If you don't want to overwrite the diffuse color but modify the existing
  11106. * values instead, use {@link module:MaterialNode.materialColor}.
  11107. *
  11108. * ```js
  11109. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11110. * ```
  11111. *
  11112. * @type {Node<vec3>?}
  11113. * @default null
  11114. */
  11115. this.colorNode = null;
  11116. /**
  11117. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11118. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11119. * and define the normals with a node instead.
  11120. *
  11121. * If you don't want to overwrite the normals but modify the existing values instead,
  11122. * use {@link module:MaterialNode.materialNormal}.
  11123. *
  11124. * @type {Node<vec3>?}
  11125. * @default null
  11126. */
  11127. this.normalNode = null;
  11128. /**
  11129. * The opacity of node materials is by default inferred from the `opacity`
  11130. * and `alphaMap` properties. This node property allows to overwrite the default
  11131. * and define the opacity with a node instead.
  11132. *
  11133. * If you don't want to overwrite the normals but modify the existing
  11134. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11135. *
  11136. * @type {Node<float>?}
  11137. * @default null
  11138. */
  11139. this.opacityNode = null;
  11140. /**
  11141. * This node can be used to to implement a variety of filter-like effects. The idea is
  11142. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11143. * to create an arbitrary effect and then assign the node composition to this property.
  11144. * Everything behind the object using this material will now be affected by a filter.
  11145. *
  11146. * ```js
  11147. * const material = new NodeMaterial()
  11148. * material.transparent = true;
  11149. *
  11150. * // everything behind the object will be monochromatic
  11151. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11152. * ```
  11153. *
  11154. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11155. *
  11156. * @type {Node<vec3>?}
  11157. * @default null
  11158. */
  11159. this.backdropNode = null;
  11160. /**
  11161. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11162. *
  11163. * @type {Node<float>?}
  11164. * @default null
  11165. */
  11166. this.backdropAlphaNode = null;
  11167. /**
  11168. * The alpha test of node materials is by default inferred from the `alphaTest`
  11169. * property. This node property allows to overwrite the default and define the
  11170. * alpha test with a node instead.
  11171. *
  11172. * If you don't want to overwrite the alpha test but modify the existing
  11173. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11174. *
  11175. * @type {Node<float>?}
  11176. * @default null
  11177. */
  11178. this.alphaTestNode = null;
  11179. /**
  11180. * The local vertex positions are computed based on multiple factors like the
  11181. * attribute data, morphing or skinning. This node property allows to overwrite
  11182. * the default and define local vertex positions with nodes instead.
  11183. *
  11184. * If you don't want to overwrite the vertex positions but modify the existing
  11185. * values instead, use {@link module:Position.positionLocal}.
  11186. *
  11187. *```js
  11188. * material.positionNode = positionLocal.add( displace );
  11189. * ```
  11190. *
  11191. * @type {Node<vec3>?}
  11192. * @default null
  11193. */
  11194. this.positionNode = null;
  11195. /**
  11196. * This node property is intended for logic which modifies geometry data once or per animation step.
  11197. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11198. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11199. * can be implemented.
  11200. *
  11201. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11202. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11203. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11204. * eventually assigned to `geometryNode`.
  11205. *
  11206. * @type {Function}
  11207. * @default null
  11208. */
  11209. this.geometryNode = null;
  11210. /**
  11211. * Allows to overwrite depth values in the fragment shader.
  11212. *
  11213. * @type {Node<float>?}
  11214. * @default null
  11215. */
  11216. this.depthNode = null;
  11217. /**
  11218. * Allows to overwrite the position used for shadow map rendering which
  11219. * is by default {@link module:Position.positionWorld}, the vertex position
  11220. * in world space.
  11221. *
  11222. * @type {Node<float>?}
  11223. * @default null
  11224. */
  11225. this.shadowPositionNode = null;
  11226. /**
  11227. * This node can be used to influence how an object using this node material
  11228. * receive shadows.
  11229. *
  11230. * ```js
  11231. * const totalShadows = float( 1 ).toVar();
  11232. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11233. * totalShadows.mulAssign( shadow );
  11234. * //return float( 1 ); // bypass received shadows
  11235. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11236. * } );
  11237. *
  11238. * @type {Node<vec4>?}
  11239. * @default null
  11240. */
  11241. this.receivedShadowNode = null;
  11242. /**
  11243. * This node can be used to influence how an object using this node material
  11244. * casts shadows. To apply a color to shadows, you can simply do:
  11245. *
  11246. * ```js
  11247. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11248. * ```
  11249. *
  11250. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11251. * is also common to use the property with `Fn` function so checks are performed
  11252. * per fragment.
  11253. *
  11254. * ```js
  11255. * materialCustomShadow.castShadowNode = Fn( () => {
  11256. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11257. * return materialColor;
  11258. * } )();
  11259. * ```
  11260. *
  11261. * @type {Node<vec4>?}
  11262. * @default null
  11263. */
  11264. this.castShadowNode = null;
  11265. /**
  11266. * This node can be used to define the final output of the material.
  11267. *
  11268. * TODO: Explain the differences to `fragmentNode`.
  11269. *
  11270. * @type {Node<vec4>?}
  11271. * @default null
  11272. */
  11273. this.outputNode = null;
  11274. /**
  11275. * MRT configuration is done on renderer or pass level. This node allows to
  11276. * overwrite what values are written into MRT targets on material level. This
  11277. * can be useful for implementing selective FX features that should only affect
  11278. * specific objects.
  11279. *
  11280. * @type {MRTNode?}
  11281. * @default null
  11282. */
  11283. this.mrtNode = null;
  11284. /**
  11285. * This node property can be used if you need complete freedom in implementing
  11286. * the fragment shader. Assigning a node will replace the built-in material
  11287. * logic used in the fragment stage.
  11288. *
  11289. * @type {Node<vec4>?}
  11290. * @default null
  11291. */
  11292. this.fragmentNode = null;
  11293. /**
  11294. * This node property can be used if you need complete freedom in implementing
  11295. * the vertex shader. Assigning a node will replace the built-in material logic
  11296. * used in the vertex stage.
  11297. *
  11298. * @type {Node<vec4>?}
  11299. * @default null
  11300. */
  11301. this.vertexNode = null;
  11302. }
  11303. /**
  11304. * Allows to define a custom cache key that influence the material key computation
  11305. * for render objects.
  11306. *
  11307. * @return {String} The custom cache key.
  11308. */
  11309. customProgramCacheKey() {
  11310. return this.type + getCacheKey$1( this );
  11311. }
  11312. /**
  11313. * Builds this material with the given node builder.
  11314. *
  11315. * @param {NodeBuilder} builder - The current node builder.
  11316. */
  11317. build( builder ) {
  11318. this.setup( builder );
  11319. }
  11320. /**
  11321. * Setups a node material observer with the given builder.
  11322. *
  11323. * @param {NodeBuilder} builder - The current node builder.
  11324. * @return {NodeMaterialObserver} The node material observer.
  11325. */
  11326. setupObserver( builder ) {
  11327. return new NodeMaterialObserver( builder );
  11328. }
  11329. /**
  11330. * Setups the vertex and fragment stage of this node material.
  11331. *
  11332. * @param {NodeBuilder} builder - The current node builder.
  11333. */
  11334. setup( builder ) {
  11335. builder.context.setupNormal = () => this.setupNormal( builder );
  11336. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11337. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11338. const renderer = builder.renderer;
  11339. const renderTarget = renderer.getRenderTarget();
  11340. // < VERTEX STAGE >
  11341. builder.addStack();
  11342. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11343. builder.stack.outputNode = vertexNode;
  11344. this.setupHardwareClipping( builder );
  11345. if ( this.geometryNode !== null ) {
  11346. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11347. }
  11348. builder.addFlow( 'vertex', builder.removeStack() );
  11349. // < FRAGMENT STAGE >
  11350. builder.addStack();
  11351. let resultNode;
  11352. const clippingNode = this.setupClipping( builder );
  11353. if ( this.depthWrite === true || this.depthTest === true ) {
  11354. // only write depth if depth buffer is configured
  11355. if ( renderTarget !== null ) {
  11356. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11357. } else {
  11358. if ( renderer.depth === true ) this.setupDepth( builder );
  11359. }
  11360. }
  11361. if ( this.fragmentNode === null ) {
  11362. this.setupDiffuseColor( builder );
  11363. this.setupVariants( builder );
  11364. const outgoingLightNode = this.setupLighting( builder );
  11365. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11366. // force unsigned floats - useful for RenderTargets
  11367. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11368. resultNode = this.setupOutput( builder, basicOutput );
  11369. // OUTPUT NODE
  11370. output.assign( resultNode );
  11371. //
  11372. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11373. // MRT
  11374. if ( renderTarget !== null ) {
  11375. const mrt = renderer.getMRT();
  11376. const materialMRT = this.mrtNode;
  11377. if ( mrt !== null ) {
  11378. resultNode = mrt;
  11379. if ( materialMRT !== null ) {
  11380. resultNode = mrt.merge( materialMRT );
  11381. }
  11382. } else if ( materialMRT !== null ) {
  11383. resultNode = materialMRT;
  11384. }
  11385. }
  11386. } else {
  11387. let fragmentNode = this.fragmentNode;
  11388. if ( fragmentNode.isOutputStructNode !== true ) {
  11389. fragmentNode = vec4( fragmentNode );
  11390. }
  11391. resultNode = this.setupOutput( builder, fragmentNode );
  11392. }
  11393. builder.stack.outputNode = resultNode;
  11394. builder.addFlow( 'fragment', builder.removeStack() );
  11395. // < OBSERVER >
  11396. builder.observer = this.setupObserver( builder );
  11397. }
  11398. /**
  11399. * Setups the clipping node.
  11400. *
  11401. * @param {NodeBuilder} builder - The current node builder.
  11402. * @return {ClippingNode} The clipping node.
  11403. */
  11404. setupClipping( builder ) {
  11405. if ( builder.clippingContext === null ) return null;
  11406. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11407. let result = null;
  11408. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11409. const samples = builder.renderer.samples;
  11410. if ( this.alphaToCoverage && samples > 1 ) {
  11411. // to be added to flow when the color/alpha value has been determined
  11412. result = clippingAlpha();
  11413. } else {
  11414. builder.stack.add( clipping() );
  11415. }
  11416. }
  11417. return result;
  11418. }
  11419. /**
  11420. * Setups the hardware clipping if available on the current device.
  11421. *
  11422. * @param {NodeBuilder} builder - The current node builder.
  11423. */
  11424. setupHardwareClipping( builder ) {
  11425. this.hardwareClipping = false;
  11426. if ( builder.clippingContext === null ) return;
  11427. const candidateCount = builder.clippingContext.unionPlanes.length;
  11428. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11429. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11430. builder.stack.add( hardwareClipping() );
  11431. this.hardwareClipping = true;
  11432. }
  11433. return;
  11434. }
  11435. /**
  11436. * Setups the depth of this material.
  11437. *
  11438. * @param {NodeBuilder} builder - The current node builder.
  11439. */
  11440. setupDepth( builder ) {
  11441. const { renderer, camera } = builder;
  11442. // Depth
  11443. let depthNode = this.depthNode;
  11444. if ( depthNode === null ) {
  11445. const mrt = renderer.getMRT();
  11446. if ( mrt && mrt.has( 'depth' ) ) {
  11447. depthNode = mrt.get( 'depth' );
  11448. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11449. if ( camera.isPerspectiveCamera ) {
  11450. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11451. } else {
  11452. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11453. }
  11454. }
  11455. }
  11456. if ( depthNode !== null ) {
  11457. depth.assign( depthNode ).append();
  11458. }
  11459. }
  11460. /**
  11461. * Setups the position node in view space. This method exists
  11462. * so derived node materials can modify the implementation e.g. sprite materials.
  11463. *
  11464. * @param {NodeBuilder} builder - The current node builder.
  11465. * @return {Node<vec3>} The position in view space.
  11466. */
  11467. setupPositionView( /*builder*/ ) {
  11468. return modelViewMatrix.mul( positionLocal ).xyz;
  11469. }
  11470. /**
  11471. * Setups the position in clip space.
  11472. *
  11473. * @param {NodeBuilder} builder - The current node builder.
  11474. * @return {Node<vec4>} The position in view space.
  11475. */
  11476. setupModelViewProjection( /*builder*/ ) {
  11477. return cameraProjectionMatrix.mul( positionView );
  11478. }
  11479. /**
  11480. * Setups the logic for the vertex stage.
  11481. *
  11482. * @param {NodeBuilder} builder - The current node builder.
  11483. * @return {Node<vec4>} The position in clip space.
  11484. */
  11485. setupVertex( builder ) {
  11486. builder.addStack();
  11487. this.setupPosition( builder );
  11488. builder.context.vertex = builder.removeStack();
  11489. return modelViewProjection;
  11490. }
  11491. /**
  11492. * Setups the computation of the position in local space.
  11493. *
  11494. * @param {NodeBuilder} builder - The current node builder.
  11495. * @return {Node<vec3>} The position in local space.
  11496. */
  11497. setupPosition( builder ) {
  11498. const { object, geometry } = builder;
  11499. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11500. morphReference( object ).append();
  11501. }
  11502. if ( object.isSkinnedMesh === true ) {
  11503. skinningReference( object ).append();
  11504. }
  11505. if ( this.displacementMap ) {
  11506. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11507. const displacementScale = materialReference( 'displacementScale', 'float' );
  11508. const displacementBias = materialReference( 'displacementBias', 'float' );
  11509. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11510. }
  11511. if ( object.isBatchedMesh ) {
  11512. batch( object ).append();
  11513. }
  11514. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11515. instancedMesh( object ).append();
  11516. }
  11517. if ( this.positionNode !== null ) {
  11518. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11519. }
  11520. return positionLocal;
  11521. }
  11522. /**
  11523. * Setups the computation of the material's diffuse color.
  11524. *
  11525. * @param {NodeBuilder} builder - The current node builder.
  11526. * @param {BufferGeometry} geometry - The geometry.
  11527. */
  11528. setupDiffuseColor( { object, geometry } ) {
  11529. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11530. // VERTEX COLORS
  11531. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11532. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11533. }
  11534. // Instanced colors
  11535. if ( object.instanceColor ) {
  11536. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11537. colorNode = instanceColor.mul( colorNode );
  11538. }
  11539. if ( object.isBatchedMesh && object._colorsTexture ) {
  11540. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11541. colorNode = batchColor.mul( colorNode );
  11542. }
  11543. // COLOR
  11544. diffuseColor.assign( colorNode );
  11545. // OPACITY
  11546. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11547. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11548. // ALPHA TEST
  11549. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11550. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11551. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11552. }
  11553. // ALPHA HASH
  11554. if ( this.alphaHash === true ) {
  11555. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11556. }
  11557. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11558. diffuseColor.a.assign( 1.0 );
  11559. }
  11560. }
  11561. /**
  11562. * Abstract interface method that can be implemented by derived materials
  11563. * to setup material-specific node variables.
  11564. *
  11565. * @abstract
  11566. * @param {NodeBuilder} builder - The current node builder.
  11567. */
  11568. setupVariants( /*builder*/ ) {
  11569. // Interface function.
  11570. }
  11571. /**
  11572. * Setups the outgoing light node variable
  11573. *
  11574. * @return {Node<vec3>} The outgoing light node.
  11575. */
  11576. setupOutgoingLight() {
  11577. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11578. }
  11579. /**
  11580. * Setups the normal node from the material.
  11581. *
  11582. * @return {Node<vec3>} The normal node.
  11583. */
  11584. setupNormal() {
  11585. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11586. }
  11587. /**
  11588. * Setups the environment node from the material.
  11589. *
  11590. * @param {NodeBuilder} builder - The current node builder.
  11591. * @return {Node<vec4>} The environment node.
  11592. */
  11593. setupEnvironment( /*builder*/ ) {
  11594. let node = null;
  11595. if ( this.envNode ) {
  11596. node = this.envNode;
  11597. } else if ( this.envMap ) {
  11598. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11599. }
  11600. return node;
  11601. }
  11602. /**
  11603. * Setups the light map node from the material.
  11604. *
  11605. * @param {NodeBuilder} builder - The current node builder.
  11606. * @return {Node<vec3>} The light map node.
  11607. */
  11608. setupLightMap( builder ) {
  11609. let node = null;
  11610. if ( builder.material.lightMap ) {
  11611. node = new IrradianceNode( materialLightMap );
  11612. }
  11613. return node;
  11614. }
  11615. /**
  11616. * Setups the lights node based on the scene, environment and material.
  11617. *
  11618. * @param {NodeBuilder} builder - The current node builder.
  11619. * @return {LightsNode} The lights node.
  11620. */
  11621. setupLights( builder ) {
  11622. const materialLightsNode = [];
  11623. //
  11624. const envNode = this.setupEnvironment( builder );
  11625. if ( envNode && envNode.isLightingNode ) {
  11626. materialLightsNode.push( envNode );
  11627. }
  11628. const lightMapNode = this.setupLightMap( builder );
  11629. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11630. materialLightsNode.push( lightMapNode );
  11631. }
  11632. if ( this.aoNode !== null || builder.material.aoMap ) {
  11633. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11634. materialLightsNode.push( new AONode( aoNode ) );
  11635. }
  11636. let lightsN = this.lightsNode || builder.lightsNode;
  11637. if ( materialLightsNode.length > 0 ) {
  11638. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11639. }
  11640. return lightsN;
  11641. }
  11642. /**
  11643. * This method should be implemented by most derived materials
  11644. * since it defines the material's lighting model.
  11645. *
  11646. * @abstract
  11647. * @param {NodeBuilder} builder - The current node builder.
  11648. * @return {LightingModel} The lighting model.
  11649. */
  11650. setupLightingModel( /*builder*/ ) {
  11651. // Interface function.
  11652. }
  11653. /**
  11654. * Setups the outgoing light node.
  11655. *
  11656. * @param {NodeBuilder} builder - The current node builder.
  11657. * @return {Node<vec3>} The outgoing light node.
  11658. */
  11659. setupLighting( builder ) {
  11660. const { material } = builder;
  11661. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11662. // OUTGOING LIGHT
  11663. const lights = this.lights === true || this.lightsNode !== null;
  11664. const lightsNode = lights ? this.setupLights( builder ) : null;
  11665. let outgoingLightNode = this.setupOutgoingLight( builder );
  11666. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11667. const lightingModel = this.setupLightingModel( builder );
  11668. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11669. } else if ( backdropNode !== null ) {
  11670. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11671. }
  11672. // EMISSIVE
  11673. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11674. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11675. outgoingLightNode = outgoingLightNode.add( emissive );
  11676. }
  11677. return outgoingLightNode;
  11678. }
  11679. /**
  11680. * Setups the output node.
  11681. *
  11682. * @param {NodeBuilder} builder - The current node builder.
  11683. * @param {Node<vec4>} outputNode - The existing output node.
  11684. * @return {Node<vec4>} The output node.
  11685. */
  11686. setupOutput( builder, outputNode ) {
  11687. // FOG
  11688. if ( this.fog === true ) {
  11689. const fogNode = builder.fogNode;
  11690. if ( fogNode ) {
  11691. output.assign( outputNode );
  11692. outputNode = vec4( fogNode );
  11693. }
  11694. }
  11695. return outputNode;
  11696. }
  11697. /**
  11698. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11699. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11700. * defining all material properties of the classic type in the node type.
  11701. *
  11702. * @param {Material} material - The material to copy properties with their values to this node material.
  11703. */
  11704. setDefaultValues( material ) {
  11705. // This approach is to reuse the native refreshUniforms*
  11706. // and turn available the use of features like transmission and environment in core
  11707. for ( const property in material ) {
  11708. const value = material[ property ];
  11709. if ( this[ property ] === undefined ) {
  11710. this[ property ] = value;
  11711. if ( value && value.clone ) this[ property ] = value.clone();
  11712. }
  11713. }
  11714. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11715. for ( const key in descriptors ) {
  11716. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11717. descriptors[ key ].get !== undefined ) {
  11718. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11719. }
  11720. }
  11721. }
  11722. /**
  11723. * Serializes this material to JSON.
  11724. *
  11725. * @param {(Object|String)?} meta - The meta information for serialization.
  11726. * @return {Object} The serialized node.
  11727. */
  11728. toJSON( meta ) {
  11729. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11730. if ( isRoot ) {
  11731. meta = {
  11732. textures: {},
  11733. images: {},
  11734. nodes: {}
  11735. };
  11736. }
  11737. const data = Material.prototype.toJSON.call( this, meta );
  11738. const nodeChildren = getNodeChildren( this );
  11739. data.inputNodes = {};
  11740. for ( const { property, childNode } of nodeChildren ) {
  11741. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11742. }
  11743. // TODO: Copied from Object3D.toJSON
  11744. function extractFromCache( cache ) {
  11745. const values = [];
  11746. for ( const key in cache ) {
  11747. const data = cache[ key ];
  11748. delete data.metadata;
  11749. values.push( data );
  11750. }
  11751. return values;
  11752. }
  11753. if ( isRoot ) {
  11754. const textures = extractFromCache( meta.textures );
  11755. const images = extractFromCache( meta.images );
  11756. const nodes = extractFromCache( meta.nodes );
  11757. if ( textures.length > 0 ) data.textures = textures;
  11758. if ( images.length > 0 ) data.images = images;
  11759. if ( nodes.length > 0 ) data.nodes = nodes;
  11760. }
  11761. return data;
  11762. }
  11763. /**
  11764. * Copies the properties of the given node material to this instance.
  11765. *
  11766. * @param {NodeMaterial} source - The material to copy.
  11767. * @return {NodeMaterial} A reference to this node material.
  11768. */
  11769. copy( source ) {
  11770. this.lightsNode = source.lightsNode;
  11771. this.envNode = source.envNode;
  11772. this.colorNode = source.colorNode;
  11773. this.normalNode = source.normalNode;
  11774. this.opacityNode = source.opacityNode;
  11775. this.backdropNode = source.backdropNode;
  11776. this.backdropAlphaNode = source.backdropAlphaNode;
  11777. this.alphaTestNode = source.alphaTestNode;
  11778. this.positionNode = source.positionNode;
  11779. this.geometryNode = source.geometryNode;
  11780. this.depthNode = source.depthNode;
  11781. this.shadowPositionNode = source.shadowPositionNode;
  11782. this.receivedShadowNode = source.receivedShadowNode;
  11783. this.castShadowNode = source.castShadowNode;
  11784. this.outputNode = source.outputNode;
  11785. this.mrtNode = source.mrtNode;
  11786. this.fragmentNode = source.fragmentNode;
  11787. this.vertexNode = source.vertexNode;
  11788. return super.copy( source );
  11789. }
  11790. }
  11791. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11792. /**
  11793. * Node material version of `LineBasicMaterial`.
  11794. *
  11795. * @augments NodeMaterial
  11796. */
  11797. class LineBasicNodeMaterial extends NodeMaterial {
  11798. static get type() {
  11799. return 'LineBasicNodeMaterial';
  11800. }
  11801. /**
  11802. * Constructs a new line basic node material.
  11803. *
  11804. * @param {Object?} parameters - The configuration parameter.
  11805. */
  11806. constructor( parameters ) {
  11807. super();
  11808. /**
  11809. * This flag can be used for type testing.
  11810. *
  11811. * @type {Boolean}
  11812. * @readonly
  11813. * @default true
  11814. */
  11815. this.isLineBasicNodeMaterial = true;
  11816. this.setDefaultValues( _defaultValues$d );
  11817. this.setValues( parameters );
  11818. }
  11819. }
  11820. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11821. /**
  11822. * Node material version of `LineDashedMaterial`.
  11823. *
  11824. * @augments NodeMaterial
  11825. */
  11826. class LineDashedNodeMaterial extends NodeMaterial {
  11827. static get type() {
  11828. return 'LineDashedNodeMaterial';
  11829. }
  11830. /**
  11831. * Constructs a new line dashed node material.
  11832. *
  11833. * @param {Object?} parameters - The configuration parameter.
  11834. */
  11835. constructor( parameters ) {
  11836. super();
  11837. /**
  11838. * This flag can be used for type testing.
  11839. *
  11840. * @type {Boolean}
  11841. * @readonly
  11842. * @default true
  11843. */
  11844. this.isLineDashedNodeMaterial = true;
  11845. this.setDefaultValues( _defaultValues$c );
  11846. /**
  11847. * The dash offset.
  11848. *
  11849. * @type {Number}
  11850. * @default 0
  11851. */
  11852. this.dashOffset = 0;
  11853. /**
  11854. * The offset of dash materials is by default inferred from the `dashOffset`
  11855. * property. This node property allows to overwrite the default
  11856. * and define the offset with a node instead.
  11857. *
  11858. * If you don't want to overwrite the offset but modify the existing
  11859. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11860. *
  11861. * @type {Node<float>?}
  11862. * @default null
  11863. */
  11864. this.offsetNode = null;
  11865. /**
  11866. * The scale of dash materials is by default inferred from the `scale`
  11867. * property. This node property allows to overwrite the default
  11868. * and define the scale with a node instead.
  11869. *
  11870. * If you don't want to overwrite the scale but modify the existing
  11871. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11872. *
  11873. * @type {Node<float>?}
  11874. * @default null
  11875. */
  11876. this.dashScaleNode = null;
  11877. /**
  11878. * The dash size of dash materials is by default inferred from the `dashSize`
  11879. * property. This node property allows to overwrite the default
  11880. * and define the dash size with a node instead.
  11881. *
  11882. * If you don't want to overwrite the dash size but modify the existing
  11883. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11884. *
  11885. * @type {Node<float>?}
  11886. * @default null
  11887. */
  11888. this.dashSizeNode = null;
  11889. /**
  11890. * The gap size of dash materials is by default inferred from the `gapSize`
  11891. * property. This node property allows to overwrite the default
  11892. * and define the gap size with a node instead.
  11893. *
  11894. * If you don't want to overwrite the gap size but modify the existing
  11895. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11896. *
  11897. * @type {Node<float>?}
  11898. * @default null
  11899. */
  11900. this.gapSizeNode = null;
  11901. this.setValues( parameters );
  11902. }
  11903. /**
  11904. * Setups the dash specific node variables.
  11905. *
  11906. * @param {NodeBuilder} builder - The current node builder.
  11907. */
  11908. setupVariants( /* builder */ ) {
  11909. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11910. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11911. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11912. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11913. dashSize.assign( dashSizeNode );
  11914. gapSize.assign( gapSizeNode );
  11915. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11916. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11917. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11918. }
  11919. }
  11920. /** @module ViewportSharedTextureNode **/
  11921. let _sharedFramebuffer = null;
  11922. /**
  11923. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11924. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11925. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11926. *
  11927. * @augments module:ViewportTextureNode~ViewportTextureNode
  11928. */
  11929. class ViewportSharedTextureNode extends ViewportTextureNode {
  11930. static get type() {
  11931. return 'ViewportSharedTextureNode';
  11932. }
  11933. /**
  11934. * Constructs a new viewport shared texture node.
  11935. *
  11936. * @param {Node} [uvNode=screenUV] - The uv node.
  11937. * @param {Node?} [levelNode=null] - The level node.
  11938. */
  11939. constructor( uvNode = screenUV, levelNode = null ) {
  11940. if ( _sharedFramebuffer === null ) {
  11941. _sharedFramebuffer = new FramebufferTexture();
  11942. }
  11943. super( uvNode, levelNode, _sharedFramebuffer );
  11944. }
  11945. updateReference() {
  11946. return this;
  11947. }
  11948. }
  11949. /**
  11950. * TSL function for creating a shared viewport texture node.
  11951. *
  11952. * @function
  11953. * @param {Node} [uvNode=screenUV] - The uv node.
  11954. * @param {Node?} [levelNode=null] - The level node.
  11955. * @returns {ViewportSharedTextureNode}
  11956. */
  11957. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11958. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11959. /**
  11960. * This node material can be used to render lines with a size larger than one
  11961. * by representing them as instanced meshes.
  11962. *
  11963. * @augments NodeMaterial
  11964. */
  11965. class Line2NodeMaterial extends NodeMaterial {
  11966. static get type() {
  11967. return 'Line2NodeMaterial';
  11968. }
  11969. /**
  11970. * Constructs a new node material for wide line rendering.
  11971. *
  11972. * @param {Object?} parameters - The configuration parameter.
  11973. */
  11974. constructor( parameters = {} ) {
  11975. super();
  11976. /**
  11977. * This flag can be used for type testing.
  11978. *
  11979. * @type {Boolean}
  11980. * @readonly
  11981. * @default true
  11982. */
  11983. this.isLine2NodeMaterial = true;
  11984. this.setDefaultValues( _defaultValues$b );
  11985. /**
  11986. * Whether vertex colors should be used or not.
  11987. *
  11988. * @type {Boolean}
  11989. * @default false
  11990. */
  11991. this.useColor = parameters.vertexColors;
  11992. /**
  11993. * The dash offset.
  11994. *
  11995. * @type {Number}
  11996. * @default 0
  11997. */
  11998. this.dashOffset = 0;
  11999. /**
  12000. * The line width.
  12001. *
  12002. * @type {Number}
  12003. * @default 0
  12004. */
  12005. this.lineWidth = 1;
  12006. /**
  12007. * Defines the lines color.
  12008. *
  12009. * @type {Node<vec3>?}
  12010. * @default null
  12011. */
  12012. this.lineColorNode = null;
  12013. /**
  12014. * Defines the offset.
  12015. *
  12016. * @type {Node<float>?}
  12017. * @default null
  12018. */
  12019. this.offsetNode = null;
  12020. /**
  12021. * Defines the dash scale.
  12022. *
  12023. * @type {Node<float>?}
  12024. * @default null
  12025. */
  12026. this.dashScaleNode = null;
  12027. /**
  12028. * Defines the dash size.
  12029. *
  12030. * @type {Node<float>?}
  12031. * @default null
  12032. */
  12033. this.dashSizeNode = null;
  12034. /**
  12035. * Defines the gap size.
  12036. *
  12037. * @type {Node<float>?}
  12038. * @default null
  12039. */
  12040. this.gapSizeNode = null;
  12041. /**
  12042. * Blending is set to `NoBlending` since transparency
  12043. * is not supported, yet.
  12044. *
  12045. * @type {Number}
  12046. * @default 0
  12047. */
  12048. this.blending = NoBlending;
  12049. this._useDash = parameters.dashed;
  12050. this._useAlphaToCoverage = true;
  12051. this._useWorldUnits = false;
  12052. this.setValues( parameters );
  12053. }
  12054. /**
  12055. * Setups the vertex and fragment stage of this node material.
  12056. *
  12057. * @param {NodeBuilder} builder - The current node builder.
  12058. */
  12059. setup( builder ) {
  12060. const { renderer } = builder;
  12061. const useAlphaToCoverage = this._useAlphaToCoverage;
  12062. const useColor = this.useColor;
  12063. const useDash = this._useDash;
  12064. const useWorldUnits = this._useWorldUnits;
  12065. const trimSegment = Fn( ( { start, end } ) => {
  12066. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12067. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12068. const nearEstimate = b.mul( -0.5 ).div( a );
  12069. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12070. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12071. } ).setLayout( {
  12072. name: 'trimSegment',
  12073. type: 'vec4',
  12074. inputs: [
  12075. { name: 'start', type: 'vec4' },
  12076. { name: 'end', type: 'vec4' }
  12077. ]
  12078. } );
  12079. this.vertexNode = Fn( () => {
  12080. const instanceStart = attribute( 'instanceStart' );
  12081. const instanceEnd = attribute( 'instanceEnd' );
  12082. // camera space
  12083. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12084. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12085. if ( useDash ) {
  12086. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12087. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12088. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12089. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12090. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12091. lineDistance = lineDistance.add( offsetNode );
  12092. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12093. }
  12094. if ( useWorldUnits ) {
  12095. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12096. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12097. }
  12098. const aspect = viewport.z.div( viewport.w );
  12099. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12100. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12101. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12102. // perhaps there is a more elegant solution -- WestLangley
  12103. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12104. If( perspective, () => {
  12105. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12106. end.assign( trimSegment( { start: start, end: end } ) );
  12107. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12108. start.assign( trimSegment( { start: end, end: start } ) );
  12109. } );
  12110. } );
  12111. // clip space
  12112. const clipStart = cameraProjectionMatrix.mul( start );
  12113. const clipEnd = cameraProjectionMatrix.mul( end );
  12114. // ndc space
  12115. const ndcStart = clipStart.xyz.div( clipStart.w );
  12116. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12117. // direction
  12118. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12119. // account for clip-space aspect ratio
  12120. dir.x.assign( dir.x.mul( aspect ) );
  12121. dir.assign( dir.normalize() );
  12122. const clip = vec4().toVar();
  12123. if ( useWorldUnits ) {
  12124. // get the offset direction as perpendicular to the view vector
  12125. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12126. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12127. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12128. const worldFwd = worldDir.cross( worldUp );
  12129. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12130. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12131. // height offset
  12132. const hw = materialLineWidth.mul( 0.5 );
  12133. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12134. // don't extend the line if we're rendering dashes because we
  12135. // won't be rendering the endcaps
  12136. if ( ! useDash ) {
  12137. // cap extension
  12138. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12139. // add width to the box
  12140. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12141. // endcaps
  12142. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12143. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12144. } );
  12145. }
  12146. // project the worldpos
  12147. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12148. // shift the depth of the projected points so the line
  12149. // segments overlap neatly
  12150. const clipPose = vec3().toVar();
  12151. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12152. clip.z.assign( clipPose.z.mul( clip.w ) );
  12153. } else {
  12154. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12155. // undo aspect ratio adjustment
  12156. dir.x.assign( dir.x.div( aspect ) );
  12157. offset.x.assign( offset.x.div( aspect ) );
  12158. // sign flip
  12159. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12160. // endcaps
  12161. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12162. offset.assign( offset.sub( dir ) );
  12163. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12164. offset.assign( offset.add( dir ) );
  12165. } );
  12166. // adjust for linewidth
  12167. offset.assign( offset.mul( materialLineWidth ) );
  12168. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12169. offset.assign( offset.div( viewport.w ) );
  12170. // select end
  12171. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12172. // back to clip space
  12173. offset.assign( offset.mul( clip.w ) );
  12174. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12175. }
  12176. return clip;
  12177. } )();
  12178. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12179. const p13 = p1.sub( p3 );
  12180. const p43 = p4.sub( p3 );
  12181. const p21 = p2.sub( p1 );
  12182. const d1343 = p13.dot( p43 );
  12183. const d4321 = p43.dot( p21 );
  12184. const d1321 = p13.dot( p21 );
  12185. const d4343 = p43.dot( p43 );
  12186. const d2121 = p21.dot( p21 );
  12187. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12188. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12189. const mua = numer.div( denom ).clamp();
  12190. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12191. return vec2( mua, mub );
  12192. } );
  12193. this.colorNode = Fn( () => {
  12194. const vUv = uv();
  12195. if ( useDash ) {
  12196. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12197. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12198. dashSize.assign( dashSizeNode );
  12199. gapSize.assign( gapSizeNode );
  12200. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12201. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12202. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12203. }
  12204. const alpha = float( 1 ).toVar( 'alpha' );
  12205. if ( useWorldUnits ) {
  12206. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12207. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12208. // Find the closest points on the view ray and the line segment
  12209. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12210. const lineDir = worldEnd.sub( worldStart );
  12211. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12212. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12213. const p2 = rayEnd.mul( params.y );
  12214. const delta = p1.sub( p2 );
  12215. const len = delta.length();
  12216. const norm = len.div( materialLineWidth );
  12217. if ( ! useDash ) {
  12218. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12219. const dnorm = norm.fwidth();
  12220. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12221. } else {
  12222. norm.greaterThan( 0.5 ).discard();
  12223. }
  12224. }
  12225. } else {
  12226. // round endcaps
  12227. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12228. const a = vUv.x;
  12229. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12230. const len2 = a.mul( a ).add( b.mul( b ) );
  12231. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12232. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12233. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12234. } );
  12235. } else {
  12236. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12237. const a = vUv.x;
  12238. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12239. const len2 = a.mul( a ).add( b.mul( b ) );
  12240. len2.greaterThan( 1.0 ).discard();
  12241. } );
  12242. }
  12243. }
  12244. let lineColorNode;
  12245. if ( this.lineColorNode ) {
  12246. lineColorNode = this.lineColorNode;
  12247. } else {
  12248. if ( useColor ) {
  12249. const instanceColorStart = attribute( 'instanceColorStart' );
  12250. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12251. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12252. lineColorNode = instanceColor.mul( materialColor );
  12253. } else {
  12254. lineColorNode = materialColor;
  12255. }
  12256. }
  12257. return vec4( lineColorNode, alpha );
  12258. } )();
  12259. if ( this.transparent ) {
  12260. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12261. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12262. }
  12263. super.setup( builder );
  12264. }
  12265. /**
  12266. * Whether the lines should sized in world units or not.
  12267. * When set to `false` the unit is pixel.
  12268. *
  12269. * @type {Boolean}
  12270. * @default false
  12271. */
  12272. get worldUnits() {
  12273. return this._useWorldUnits;
  12274. }
  12275. set worldUnits( value ) {
  12276. if ( this._useWorldUnits !== value ) {
  12277. this._useWorldUnits = value;
  12278. this.needsUpdate = true;
  12279. }
  12280. }
  12281. /**
  12282. * Whether the lines should be dashed or not.
  12283. *
  12284. * @type {Boolean}
  12285. * @default false
  12286. */
  12287. get dashed() {
  12288. return this._useDash;
  12289. }
  12290. set dashed( value ) {
  12291. if ( this._useDash !== value ) {
  12292. this._useDash = value;
  12293. this.needsUpdate = true;
  12294. }
  12295. }
  12296. /**
  12297. * Whether alpha to coverage should be used or not.
  12298. *
  12299. * @type {Boolean}
  12300. * @default true
  12301. */
  12302. get alphaToCoverage() {
  12303. return this._useAlphaToCoverage;
  12304. }
  12305. set alphaToCoverage( value ) {
  12306. if ( this._useAlphaToCoverage !== value ) {
  12307. this._useAlphaToCoverage = value;
  12308. this.needsUpdate = true;
  12309. }
  12310. }
  12311. }
  12312. /** @module Packing **/
  12313. /**
  12314. * Packs a direction vector into a color value.
  12315. *
  12316. * @method
  12317. * @param {Node<vec3>} node - The direction to pack.
  12318. * @return {Node<vec3>} The color.
  12319. */
  12320. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12321. /**
  12322. * Unpacks a color value into a direction vector.
  12323. *
  12324. * @method
  12325. * @param {Node<vec3>} node - The color to unpack.
  12326. * @return {Node<vec3>} The direction.
  12327. */
  12328. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12329. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12330. /**
  12331. * Node material version of `MeshNormalMaterial`.
  12332. *
  12333. * @augments NodeMaterial
  12334. */
  12335. class MeshNormalNodeMaterial extends NodeMaterial {
  12336. static get type() {
  12337. return 'MeshNormalNodeMaterial';
  12338. }
  12339. /**
  12340. * Constructs a new mesh normal node material.
  12341. *
  12342. * @param {Object?} parameters - The configuration parameter.
  12343. */
  12344. constructor( parameters ) {
  12345. super();
  12346. /**
  12347. * This flag can be used for type testing.
  12348. *
  12349. * @type {Boolean}
  12350. * @readonly
  12351. * @default true
  12352. */
  12353. this.isMeshNormalNodeMaterial = true;
  12354. this.setDefaultValues( _defaultValues$a );
  12355. this.setValues( parameters );
  12356. }
  12357. /**
  12358. * Overwrites the default implementation by computing the diffuse color
  12359. * based on the normal data.
  12360. */
  12361. setupDiffuseColor() {
  12362. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12363. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12364. }
  12365. }
  12366. /** @module EquirectUVNode **/
  12367. /**
  12368. * Can be used to compute texture coordinates for projecting an
  12369. * equirectangular texture onto a mesh for using it as the scene's
  12370. * background.
  12371. *
  12372. * ```js
  12373. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12374. * ```
  12375. *
  12376. * @augments TempNode
  12377. */
  12378. class EquirectUVNode extends TempNode {
  12379. static get type() {
  12380. return 'EquirectUVNode';
  12381. }
  12382. /**
  12383. * Constructs a new equirect uv node.
  12384. *
  12385. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12386. */
  12387. constructor( dirNode = positionWorldDirection ) {
  12388. super( 'vec2' );
  12389. /**
  12390. * A direction vector for sampling why is by default `positionWorldDirection`.
  12391. *
  12392. * @type {Node<vec3>}
  12393. */
  12394. this.dirNode = dirNode;
  12395. }
  12396. setup() {
  12397. const dir = this.dirNode;
  12398. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12399. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12400. return vec2( u, v );
  12401. }
  12402. }
  12403. /**
  12404. * TSL function for creating an equirect uv node.
  12405. *
  12406. * @function
  12407. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12408. * @returns {EquirectUVNode}
  12409. */
  12410. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12411. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12412. /**
  12413. * This class represents a cube render target. It is a special version
  12414. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12415. *
  12416. * @augments WebGLCubeRenderTarget
  12417. */
  12418. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12419. constructor( size = 1, options = {} ) {
  12420. super( size, options );
  12421. this.isCubeRenderTarget = true;
  12422. }
  12423. /**
  12424. * Converts the given equirectangular texture to a cube map.
  12425. *
  12426. * @param {Renderer} renderer - The renderer.
  12427. * @param {Texture} texture - The equirectangular texture.
  12428. * @return {CubeRenderTarget} A reference to this cube render target.
  12429. */
  12430. fromEquirectangularTexture( renderer, texture$1 ) {
  12431. const currentMinFilter = texture$1.minFilter;
  12432. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12433. texture$1.generateMipmaps = true;
  12434. this.texture.type = texture$1.type;
  12435. this.texture.colorSpace = texture$1.colorSpace;
  12436. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12437. this.texture.minFilter = texture$1.minFilter;
  12438. this.texture.magFilter = texture$1.magFilter;
  12439. const geometry = new BoxGeometry( 5, 5, 5 );
  12440. const uvNode = equirectUV( positionWorldDirection );
  12441. const material = new NodeMaterial();
  12442. material.colorNode = texture( texture$1, uvNode, 0 );
  12443. material.side = BackSide;
  12444. material.blending = NoBlending;
  12445. const mesh = new Mesh( geometry, material );
  12446. const scene = new Scene();
  12447. scene.add( mesh );
  12448. // Avoid blurred poles
  12449. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12450. const camera = new CubeCamera( 1, 10, this );
  12451. const currentMRT = renderer.getMRT();
  12452. renderer.setMRT( null );
  12453. camera.update( renderer, scene );
  12454. renderer.setMRT( currentMRT );
  12455. texture$1.minFilter = currentMinFilter;
  12456. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12457. mesh.geometry.dispose();
  12458. mesh.material.dispose();
  12459. return this;
  12460. }
  12461. }
  12462. /** @module CubeMapNode **/
  12463. const _cache$1 = new WeakMap();
  12464. /**
  12465. * This node can be used to automatically convert environment maps in the
  12466. * equirectangular format into the cube map format.
  12467. *
  12468. * @augments TempNode
  12469. */
  12470. class CubeMapNode extends TempNode {
  12471. static get type() {
  12472. return 'CubeMapNode';
  12473. }
  12474. /**
  12475. * Constructs a new cube map node.
  12476. *
  12477. * @param {Node} envNode - The node representing the environment map.
  12478. */
  12479. constructor( envNode ) {
  12480. super( 'vec3' );
  12481. /**
  12482. * The node representing the environment map.
  12483. *
  12484. * @type {Node}
  12485. */
  12486. this.envNode = envNode;
  12487. /**
  12488. * A reference to the internal cube texture.
  12489. *
  12490. * @private
  12491. * @type {CubeTexture}
  12492. * @default null
  12493. */
  12494. this._cubeTexture = null;
  12495. /**
  12496. * A reference to the internal cube texture node.
  12497. *
  12498. * @private
  12499. * @type {CubeTextureNode}
  12500. */
  12501. this._cubeTextureNode = cubeTexture();
  12502. const defaultTexture = new CubeTexture();
  12503. defaultTexture.isRenderTargetTexture = true;
  12504. /**
  12505. * A default cube texture that acts as a placeholder.
  12506. * It is used when the conversion from equirectangular to cube
  12507. * map has not finished yet for a given texture.
  12508. *
  12509. * @private
  12510. * @type {CubeTexture}
  12511. */
  12512. this._defaultTexture = defaultTexture;
  12513. /**
  12514. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12515. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12516. *
  12517. * @type {String}
  12518. * @default 'render'
  12519. */
  12520. this.updateBeforeType = NodeUpdateType.RENDER;
  12521. }
  12522. updateBefore( frame ) {
  12523. const { renderer, material } = frame;
  12524. const envNode = this.envNode;
  12525. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12526. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12527. if ( texture && texture.isTexture ) {
  12528. const mapping = texture.mapping;
  12529. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12530. // check for converted cubemap map
  12531. if ( _cache$1.has( texture ) ) {
  12532. const cubeMap = _cache$1.get( texture );
  12533. mapTextureMapping( cubeMap, texture.mapping );
  12534. this._cubeTexture = cubeMap;
  12535. } else {
  12536. // create cube map from equirectangular map
  12537. const image = texture.image;
  12538. if ( isEquirectangularMapReady$1( image ) ) {
  12539. const renderTarget = new CubeRenderTarget( image.height );
  12540. renderTarget.fromEquirectangularTexture( renderer, texture );
  12541. mapTextureMapping( renderTarget.texture, texture.mapping );
  12542. this._cubeTexture = renderTarget.texture;
  12543. _cache$1.set( texture, renderTarget.texture );
  12544. texture.addEventListener( 'dispose', onTextureDispose );
  12545. } else {
  12546. // default cube texture as fallback when equirectangular texture is not yet loaded
  12547. this._cubeTexture = this._defaultTexture;
  12548. }
  12549. }
  12550. //
  12551. this._cubeTextureNode.value = this._cubeTexture;
  12552. } else {
  12553. // envNode already refers to a cube map
  12554. this._cubeTextureNode = this.envNode;
  12555. }
  12556. }
  12557. }
  12558. }
  12559. setup( builder ) {
  12560. this.updateBefore( builder );
  12561. return this._cubeTextureNode;
  12562. }
  12563. }
  12564. /**
  12565. * Returns true if the given equirectangular image has been fully loaded
  12566. * and is ready for further processing.
  12567. *
  12568. * @private
  12569. * @param {Image} image - The equirectangular image to check.
  12570. * @return {Boolean} Whether the image is ready or not.
  12571. */
  12572. function isEquirectangularMapReady$1( image ) {
  12573. if ( image === null || image === undefined ) return false;
  12574. return image.height > 0;
  12575. }
  12576. /**
  12577. * This function is executed when `dispose()` is called on the equirectangular
  12578. * texture. In this case, the generated cube map with its render target
  12579. * is deleted as well.
  12580. *
  12581. * @private
  12582. * @param {Object} event - The event object.
  12583. */
  12584. function onTextureDispose( event ) {
  12585. const texture = event.target;
  12586. texture.removeEventListener( 'dispose', onTextureDispose );
  12587. const renderTarget = _cache$1.get( texture );
  12588. if ( renderTarget !== undefined ) {
  12589. _cache$1.delete( texture );
  12590. renderTarget.dispose();
  12591. }
  12592. }
  12593. /**
  12594. * This function makes sure the generated cube map uses the correct
  12595. * texture mapping that corresponds to the equirectangular original.
  12596. *
  12597. * @private
  12598. * @param {Texture} texture - The cube texture.
  12599. * @param {Number} mapping - The original texture mapping.
  12600. */
  12601. function mapTextureMapping( texture, mapping ) {
  12602. if ( mapping === EquirectangularReflectionMapping ) {
  12603. texture.mapping = CubeReflectionMapping;
  12604. } else if ( mapping === EquirectangularRefractionMapping ) {
  12605. texture.mapping = CubeRefractionMapping;
  12606. }
  12607. }
  12608. /**
  12609. * TSL function for creating a cube map node.
  12610. *
  12611. * @function
  12612. * @param {Node} envNode - The node representing the environment map.
  12613. * @returns {CubeMapNode}
  12614. */
  12615. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12616. /**
  12617. * Represents a basic model for Image-based lighting (IBL). The environment
  12618. * is defined via environment maps in the equirectangular or cube map format.
  12619. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12620. * or {@link MeshPhongNodeMaterial}.
  12621. *
  12622. * @augments LightingNode
  12623. */
  12624. class BasicEnvironmentNode extends LightingNode {
  12625. static get type() {
  12626. return 'BasicEnvironmentNode';
  12627. }
  12628. /**
  12629. * Constructs a new basic environment node.
  12630. *
  12631. * @param {Node} [envNode=null] - A node representing the environment.
  12632. */
  12633. constructor( envNode = null ) {
  12634. super();
  12635. /**
  12636. * A node representing the environment.
  12637. *
  12638. * @type {Node}
  12639. * @default null
  12640. */
  12641. this.envNode = envNode;
  12642. }
  12643. setup( builder ) {
  12644. // environment property is used in the finish() method of BasicLightingModel
  12645. builder.context.environment = cubeMapNode( this.envNode );
  12646. }
  12647. }
  12648. /**
  12649. * A specific version of {@link IrradianceNode} that is only relevant
  12650. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12651. * requires a special scaling factor for the light map.
  12652. *
  12653. * @augments LightingNode
  12654. */
  12655. class BasicLightMapNode extends LightingNode {
  12656. static get type() {
  12657. return 'BasicLightMapNode';
  12658. }
  12659. /**
  12660. * Constructs a new basic light map node.
  12661. *
  12662. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12663. */
  12664. constructor( lightMapNode = null ) {
  12665. super();
  12666. /**
  12667. * The light map node.
  12668. *
  12669. * @type {Node<vec3>?}
  12670. */
  12671. this.lightMapNode = lightMapNode;
  12672. }
  12673. setup( builder ) {
  12674. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12675. const RECIPROCAL_PI = float( 1 / Math.PI );
  12676. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12677. }
  12678. }
  12679. /**
  12680. * Abstract class for implementing lighting models. The module defines
  12681. * multiple methods that concrete lighting models can implement. These
  12682. * methods are executed at different points during the light evaluation
  12683. * process.
  12684. */
  12685. class LightingModel {
  12686. /**
  12687. * This method is intended for setting up lighting model and context data
  12688. * which are later used in the evaluation process.
  12689. *
  12690. * @abstract
  12691. * @param {ContextNode} input - The current node context.
  12692. * @param {StackNode} stack - The current stack.
  12693. * @param {NodeBuilder} builder - The current node builder.
  12694. */
  12695. start( /*input, stack, builder*/ ) { }
  12696. /**
  12697. * This method is intended for executing final tasks like final updates
  12698. * to the outgoing light.
  12699. *
  12700. * @abstract
  12701. * @param {ContextNode} input - The current node context.
  12702. * @param {StackNode} stack - The current stack.
  12703. * @param {NodeBuilder} builder - The current node builder.
  12704. */
  12705. finish( /*input, stack, builder*/ ) { }
  12706. /**
  12707. * This method is intended for implementing the direct light term and
  12708. * executed during the build process of directional, point and spot light nodes.
  12709. *
  12710. * @abstract
  12711. * @param {Object} input - The input data.
  12712. * @param {StackNode} stack - The current stack.
  12713. * @param {NodeBuilder} builder - The current node builder.
  12714. */
  12715. direct( /*input, stack, builder*/ ) { }
  12716. /**
  12717. * This method is intended for implementing the direct light term for
  12718. * rect area light nodes.
  12719. *
  12720. * @abstract
  12721. * @param {Object} input - The input data.
  12722. * @param {StackNode} stack - The current stack.
  12723. * @param {NodeBuilder} builder - The current node builder.
  12724. */
  12725. directRectArea( /*input, stack, builder*/ ) {}
  12726. /**
  12727. * This method is intended for implementing the indirect light term.
  12728. *
  12729. * @abstract
  12730. * @param {ContextNode} input - The current node context.
  12731. * @param {StackNode} stack - The current stack.
  12732. * @param {NodeBuilder} builder - The current node builder.
  12733. */
  12734. indirect( /*input, stack, builder*/ ) { }
  12735. /**
  12736. * This method is intended for implementing the ambient occlusion term.
  12737. * Unlike other methods, this method must be called manually by the lighting
  12738. * model in its indirect term.
  12739. *
  12740. * @abstract
  12741. * @param {ContextNode} input - The current node context.
  12742. * @param {StackNode} stack - The current stack.
  12743. * @param {NodeBuilder} builder - The current node builder.
  12744. */
  12745. ambientOcclusion( /*input, stack, builder*/ ) { }
  12746. }
  12747. /**
  12748. * Represents the lighting model for unlit materials. The only light contribution
  12749. * is baked indirect lighting modulated with ambient occlusion and the material's
  12750. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12751. *
  12752. * @augments LightingModel
  12753. */
  12754. class BasicLightingModel extends LightingModel {
  12755. /**
  12756. * Constructs a new basic lighting model.
  12757. */
  12758. constructor() {
  12759. super();
  12760. }
  12761. /**
  12762. * Implements the baked indirect lighting with its modulation.
  12763. *
  12764. * @param {ContextNode} context - The current node context.
  12765. * @param {StackNode} stack - The current stack.
  12766. * @param {NodeBuilder} builder - The current node builder.
  12767. */
  12768. indirect( context, stack, builder ) {
  12769. const ambientOcclusion = context.ambientOcclusion;
  12770. const reflectedLight = context.reflectedLight;
  12771. const irradianceLightMap = builder.context.irradianceLightMap;
  12772. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12773. // accumulation (baked indirect lighting only)
  12774. if ( irradianceLightMap ) {
  12775. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12776. } else {
  12777. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12778. }
  12779. // modulation
  12780. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12781. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12782. }
  12783. /**
  12784. * Implements the environment mapping.
  12785. *
  12786. * @param {ContextNode} context - The current node context.
  12787. * @param {StackNode} stack - The current stack.
  12788. * @param {NodeBuilder} builder - The current node builder.
  12789. */
  12790. finish( context, stack, builder ) {
  12791. const material = builder.material;
  12792. const outgoingLight = context.outgoingLight;
  12793. const envNode = builder.context.environment;
  12794. if ( envNode ) {
  12795. switch ( material.combine ) {
  12796. case MultiplyOperation:
  12797. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12798. break;
  12799. case MixOperation:
  12800. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12801. break;
  12802. case AddOperation:
  12803. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12804. break;
  12805. default:
  12806. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12807. break;
  12808. }
  12809. }
  12810. }
  12811. }
  12812. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12813. /**
  12814. * Node material version of `MeshBasicMaterial`.
  12815. *
  12816. * @augments NodeMaterial
  12817. */
  12818. class MeshBasicNodeMaterial extends NodeMaterial {
  12819. static get type() {
  12820. return 'MeshBasicNodeMaterial';
  12821. }
  12822. /**
  12823. * Constructs a new mesh basic node material.
  12824. *
  12825. * @param {Object?} parameters - The configuration parameter.
  12826. */
  12827. constructor( parameters ) {
  12828. super();
  12829. /**
  12830. * This flag can be used for type testing.
  12831. *
  12832. * @type {Boolean}
  12833. * @readonly
  12834. * @default true
  12835. */
  12836. this.isMeshBasicNodeMaterial = true;
  12837. /**
  12838. * Although the basic material is by definition unlit, we set
  12839. * this property to `true` since we use a lighting model to compute
  12840. * the outgoing light of the fragment shader.
  12841. *
  12842. * @type {Boolean}
  12843. * @default true
  12844. */
  12845. this.lights = true;
  12846. this.setDefaultValues( _defaultValues$9 );
  12847. this.setValues( parameters );
  12848. }
  12849. /**
  12850. * Basic materials are not affected by normal and bump maps so we
  12851. * return by default {@link module:Normal.normalView}.
  12852. *
  12853. * @return {Node<vec3>} The normal node.
  12854. */
  12855. setupNormal() {
  12856. return normalView; // see #28839
  12857. }
  12858. /**
  12859. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12860. * to implement the default environment mapping.
  12861. *
  12862. * @param {NodeBuilder} builder - The current node builder.
  12863. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12864. */
  12865. setupEnvironment( builder ) {
  12866. const envNode = super.setupEnvironment( builder );
  12867. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12868. }
  12869. /**
  12870. * This method must be overwritten since light maps are evaluated
  12871. * with a special scaling factor for basic materials.
  12872. *
  12873. * @param {NodeBuilder} builder - The current node builder.
  12874. * @return {BasicLightMapNode<vec3>?} The light map node.
  12875. */
  12876. setupLightMap( builder ) {
  12877. let node = null;
  12878. if ( builder.material.lightMap ) {
  12879. node = new BasicLightMapNode( materialLightMap );
  12880. }
  12881. return node;
  12882. }
  12883. /**
  12884. * The material overwrites this method because `lights` is set to `true` but
  12885. * we still want to return the diffuse color as the outgoing light.
  12886. *
  12887. * @return {Node<vec3>} The outgoing light node.
  12888. */
  12889. setupOutgoingLight() {
  12890. return diffuseColor.rgb;
  12891. }
  12892. /**
  12893. * Setups the lighting model.
  12894. *
  12895. * @return {BasicLightingModel} The lighting model.
  12896. */
  12897. setupLightingModel() {
  12898. return new BasicLightingModel();
  12899. }
  12900. }
  12901. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12902. // Original approximation by Christophe Schlick '94
  12903. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12904. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12905. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12906. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12907. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12908. } ); // validated
  12909. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12910. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12911. } ); // validated
  12912. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12913. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12914. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12915. } );
  12916. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12917. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12918. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12919. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12920. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12921. const G = G_BlinnPhong_Implicit();
  12922. const D = D_BlinnPhong( { dotNH } );
  12923. return F.mul( G ).mul( D );
  12924. } );
  12925. /**
  12926. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12927. *
  12928. * @augments BasicLightingModel
  12929. */
  12930. class PhongLightingModel extends BasicLightingModel {
  12931. /**
  12932. * Constructs a new phong lighting model.
  12933. *
  12934. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12935. */
  12936. constructor( specular = true ) {
  12937. super();
  12938. /**
  12939. * Whether specular is supported or not. Set this to `false` if you are
  12940. * looking for a Lambert-like material meaning a material for non-shiny
  12941. * surfaces, without specular highlights.
  12942. *
  12943. * @type {Boolean}
  12944. * @default true
  12945. */
  12946. this.specular = specular;
  12947. }
  12948. /**
  12949. * Implements the direct lighting. The specular portion is optional an can be controlled
  12950. * with the {@link PhongLightingModel#specular} flag.
  12951. *
  12952. * @param {Object} input - The input data.
  12953. * @param {StackNode} stack - The current stack.
  12954. * @param {NodeBuilder} builder - The current node builder.
  12955. */
  12956. direct( { lightDirection, lightColor, reflectedLight } ) {
  12957. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12958. const irradiance = dotNL.mul( lightColor );
  12959. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12960. if ( this.specular === true ) {
  12961. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12962. }
  12963. }
  12964. /**
  12965. * Implements the indirect lighting.
  12966. *
  12967. * @param {ContextNode} input - The current node context.
  12968. * @param {StackNode} stack - The current stack.
  12969. * @param {NodeBuilder} builder - The current node builder.
  12970. */
  12971. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12972. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12973. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12974. }
  12975. }
  12976. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12977. /**
  12978. * Node material version of `MeshLambertMaterial`.
  12979. *
  12980. * @augments NodeMaterial
  12981. */
  12982. class MeshLambertNodeMaterial extends NodeMaterial {
  12983. static get type() {
  12984. return 'MeshLambertNodeMaterial';
  12985. }
  12986. /**
  12987. * Constructs a new mesh lambert node material.
  12988. *
  12989. * @param {Object?} parameters - The configuration parameter.
  12990. */
  12991. constructor( parameters ) {
  12992. super();
  12993. /**
  12994. * This flag can be used for type testing.
  12995. *
  12996. * @type {Boolean}
  12997. * @readonly
  12998. * @default true
  12999. */
  13000. this.isMeshLambertNodeMaterial = true;
  13001. /**
  13002. * Set to `true` because lambert materials react on lights.
  13003. *
  13004. * @type {Boolean}
  13005. * @default true
  13006. */
  13007. this.lights = true;
  13008. this.setDefaultValues( _defaultValues$8 );
  13009. this.setValues( parameters );
  13010. }
  13011. /**
  13012. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13013. * to implement the default environment mapping.
  13014. *
  13015. * @param {NodeBuilder} builder - The current node builder.
  13016. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13017. */
  13018. setupEnvironment( builder ) {
  13019. const envNode = super.setupEnvironment( builder );
  13020. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13021. }
  13022. /**
  13023. * Setups the lighting model.
  13024. *
  13025. * @return {PhongLightingModel} The lighting model.
  13026. */
  13027. setupLightingModel( /*builder*/ ) {
  13028. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13029. }
  13030. }
  13031. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13032. /**
  13033. * Node material version of `MeshPhongMaterial`.
  13034. *
  13035. * @augments NodeMaterial
  13036. */
  13037. class MeshPhongNodeMaterial extends NodeMaterial {
  13038. static get type() {
  13039. return 'MeshPhongNodeMaterial';
  13040. }
  13041. /**
  13042. * Constructs a new mesh lambert node material.
  13043. *
  13044. * @param {Object?} parameters - The configuration parameter.
  13045. */
  13046. constructor( parameters ) {
  13047. super();
  13048. /**
  13049. * This flag can be used for type testing.
  13050. *
  13051. * @type {Boolean}
  13052. * @readonly
  13053. * @default true
  13054. */
  13055. this.isMeshPhongNodeMaterial = true;
  13056. /**
  13057. * Set to `true` because phong materials react on lights.
  13058. *
  13059. * @type {Boolean}
  13060. * @default true
  13061. */
  13062. this.lights = true;
  13063. /**
  13064. * The shininess of phong materials is by default inferred from the `shininess`
  13065. * property. This node property allows to overwrite the default
  13066. * and define the shininess with a node instead.
  13067. *
  13068. * If you don't want to overwrite the shininess but modify the existing
  13069. * value instead, use {@link module:MaterialNode.materialShininess}.
  13070. *
  13071. * @type {Node<float>?}
  13072. * @default null
  13073. */
  13074. this.shininessNode = null;
  13075. /**
  13076. * The specular color of phong materials is by default inferred from the
  13077. * `specular` property. This node property allows to overwrite the default
  13078. * and define the specular color with a node instead.
  13079. *
  13080. * If you don't want to overwrite the specular color but modify the existing
  13081. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13082. *
  13083. * @type {Node<vec3>?}
  13084. * @default null
  13085. */
  13086. this.specularNode = null;
  13087. this.setDefaultValues( _defaultValues$7 );
  13088. this.setValues( parameters );
  13089. }
  13090. /**
  13091. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13092. * to implement the default environment mapping.
  13093. *
  13094. * @param {NodeBuilder} builder - The current node builder.
  13095. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13096. */
  13097. setupEnvironment( builder ) {
  13098. const envNode = super.setupEnvironment( builder );
  13099. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13100. }
  13101. /**
  13102. * Setups the lighting model.
  13103. *
  13104. * @return {PhongLightingModel} The lighting model.
  13105. */
  13106. setupLightingModel( /*builder*/ ) {
  13107. return new PhongLightingModel();
  13108. }
  13109. /**
  13110. * Setups the phong specific node variables.
  13111. *
  13112. * @param {NodeBuilder} builder - The current node builder.
  13113. */
  13114. setupVariants( /*builder*/ ) {
  13115. // SHININESS
  13116. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13117. shininess.assign( shininessNode );
  13118. // SPECULAR COLOR
  13119. const specularNode = this.specularNode || materialSpecular;
  13120. specularColor.assign( specularNode );
  13121. }
  13122. copy( source ) {
  13123. this.shininessNode = source.shininessNode;
  13124. this.specularNode = source.specularNode;
  13125. return super.copy( source );
  13126. }
  13127. }
  13128. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13129. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13130. return float( 0 );
  13131. }
  13132. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13133. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13134. return geometryRoughness;
  13135. } );
  13136. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13137. const { roughness } = inputs;
  13138. const geometryRoughness = getGeometryRoughness();
  13139. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13140. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13141. roughnessFactor = roughnessFactor.min( 1.0 );
  13142. return roughnessFactor;
  13143. } );
  13144. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13145. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13146. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13147. const a2 = alpha.pow2();
  13148. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13149. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13150. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13151. } ).setLayout( {
  13152. name: 'V_GGX_SmithCorrelated',
  13153. type: 'float',
  13154. inputs: [
  13155. { name: 'alpha', type: 'float' },
  13156. { name: 'dotNL', type: 'float' },
  13157. { name: 'dotNV', type: 'float' }
  13158. ]
  13159. } ); // validated
  13160. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13161. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13162. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13163. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13164. const v = div( 0.5, gv.add( gl ) );
  13165. return v.saturate();
  13166. } ).setLayout( {
  13167. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13168. type: 'float',
  13169. inputs: [
  13170. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13171. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13172. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13173. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13174. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13175. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13176. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13177. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13178. ]
  13179. } );
  13180. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13181. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13182. // alpha is "roughness squared" in Disney’s reparameterization
  13183. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13184. const a2 = alpha.pow2();
  13185. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13186. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13187. } ).setLayout( {
  13188. name: 'D_GGX',
  13189. type: 'float',
  13190. inputs: [
  13191. { name: 'alpha', type: 'float' },
  13192. { name: 'dotNH', type: 'float' }
  13193. ]
  13194. } ); // validated
  13195. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13196. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13197. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13198. const a2 = alphaT.mul( alphaB );
  13199. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13200. const v2 = v.dot( v );
  13201. const w2 = a2.div( v2 );
  13202. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13203. } ).setLayout( {
  13204. name: 'D_GGX_Anisotropic',
  13205. type: 'float',
  13206. inputs: [
  13207. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13208. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13209. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13210. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13211. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13212. ]
  13213. } );
  13214. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13215. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13216. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13217. const normalView = inputs.normalView || transformedNormalView;
  13218. const alpha = roughness.pow2(); // UE4's roughness
  13219. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13220. const dotNL = normalView.dot( lightDirection ).clamp();
  13221. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13222. const dotNH = normalView.dot( halfDir ).clamp();
  13223. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13224. let F = F_Schlick( { f0, f90, dotVH } );
  13225. let V, D;
  13226. if ( defined( USE_IRIDESCENCE ) ) {
  13227. F = iridescence.mix( F, f );
  13228. }
  13229. if ( defined( USE_ANISOTROPY ) ) {
  13230. const dotTL = anisotropyT.dot( lightDirection );
  13231. const dotTV = anisotropyT.dot( positionViewDirection );
  13232. const dotTH = anisotropyT.dot( halfDir );
  13233. const dotBL = anisotropyB.dot( lightDirection );
  13234. const dotBV = anisotropyB.dot( positionViewDirection );
  13235. const dotBH = anisotropyB.dot( halfDir );
  13236. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13237. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13238. } else {
  13239. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13240. D = D_GGX( { alpha, dotNH } );
  13241. }
  13242. return F.mul( V ).mul( D );
  13243. } ); // validated
  13244. // Analytical approximation of the DFG LUT, one half of the
  13245. // split-sum approximation used in indirect specular lighting.
  13246. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13247. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13248. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13249. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13250. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13251. const r = roughness.mul( c0 ).add( c1 );
  13252. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13253. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13254. return fab;
  13255. } ).setLayout( {
  13256. name: 'DFGApprox',
  13257. type: 'vec2',
  13258. inputs: [
  13259. { name: 'roughness', type: 'float' },
  13260. { name: 'dotNV', type: 'vec3' }
  13261. ]
  13262. } );
  13263. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13264. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13265. const fab = DFGApprox( { dotNV, roughness } );
  13266. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13267. } );
  13268. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13269. const x = dotVH.oneMinus().saturate();
  13270. const x2 = x.mul( x );
  13271. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13272. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13273. } ).setLayout( {
  13274. name: 'Schlick_to_F0',
  13275. type: 'vec3',
  13276. inputs: [
  13277. { name: 'f', type: 'vec3' },
  13278. { name: 'f90', type: 'float' },
  13279. { name: 'dotVH', type: 'float' }
  13280. ]
  13281. } );
  13282. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13283. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13284. const alpha = roughness.pow2();
  13285. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13286. const invAlpha = float( 1.0 ).div( alpha );
  13287. const cos2h = dotNH.pow2();
  13288. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13289. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13290. } ).setLayout( {
  13291. name: 'D_Charlie',
  13292. type: 'float',
  13293. inputs: [
  13294. { name: 'roughness', type: 'float' },
  13295. { name: 'dotNH', type: 'float' }
  13296. ]
  13297. } );
  13298. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13299. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13300. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13301. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13302. } ).setLayout( {
  13303. name: 'V_Neubelt',
  13304. type: 'float',
  13305. inputs: [
  13306. { name: 'dotNV', type: 'float' },
  13307. { name: 'dotNL', type: 'float' }
  13308. ]
  13309. } );
  13310. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13311. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13312. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13313. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13314. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13315. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13316. const V = V_Neubelt( { dotNV, dotNL } );
  13317. return sheen.mul( D ).mul( V );
  13318. } );
  13319. // Rect Area Light
  13320. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13321. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13322. // code: https://github.com/selfshadow/ltc_code/
  13323. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13324. const LUT_SIZE = 64.0;
  13325. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13326. const LUT_BIAS = 0.5 / LUT_SIZE;
  13327. const dotNV = N.dot( V ).saturate();
  13328. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13329. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13330. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13331. return uv;
  13332. } ).setLayout( {
  13333. name: 'LTC_Uv',
  13334. type: 'vec2',
  13335. inputs: [
  13336. { name: 'N', type: 'vec3' },
  13337. { name: 'V', type: 'vec3' },
  13338. { name: 'roughness', type: 'float' }
  13339. ]
  13340. } );
  13341. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13342. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13343. // An approximation of the form factor of a horizon-clipped rectangle.
  13344. const l = f.length();
  13345. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13346. } ).setLayout( {
  13347. name: 'LTC_ClippedSphereFormFactor',
  13348. type: 'float',
  13349. inputs: [
  13350. { name: 'f', type: 'vec3' }
  13351. ]
  13352. } );
  13353. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13354. const x = v1.dot( v2 );
  13355. const y = x.abs().toVar();
  13356. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13357. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13358. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13359. const v = a.div( b );
  13360. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13361. return v1.cross( v2 ).mul( theta_sintheta );
  13362. } ).setLayout( {
  13363. name: 'LTC_EdgeVectorFormFactor',
  13364. type: 'vec3',
  13365. inputs: [
  13366. { name: 'v1', type: 'vec3' },
  13367. { name: 'v2', type: 'vec3' }
  13368. ]
  13369. } );
  13370. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13371. // bail if point is on back side of plane of light
  13372. // assumes ccw winding order of light vertices
  13373. const v1 = p1.sub( p0 ).toVar();
  13374. const v2 = p3.sub( p0 ).toVar();
  13375. const lightNormal = v1.cross( v2 );
  13376. const result = vec3().toVar();
  13377. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13378. // construct orthonormal basis around N
  13379. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13380. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13381. // compute transform
  13382. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13383. // transform rect
  13384. // & project rect onto sphere
  13385. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13386. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13387. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13388. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13389. // calculate vector form factor
  13390. const vectorFormFactor = vec3( 0 ).toVar();
  13391. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13392. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13393. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13394. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13395. // adjust for horizon clipping
  13396. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13397. } );
  13398. return result;
  13399. } ).setLayout( {
  13400. name: 'LTC_Evaluate',
  13401. type: 'vec3',
  13402. inputs: [
  13403. { name: 'N', type: 'vec3' },
  13404. { name: 'V', type: 'vec3' },
  13405. { name: 'P', type: 'vec3' },
  13406. { name: 'mInv', type: 'mat3' },
  13407. { name: 'p0', type: 'vec3' },
  13408. { name: 'p1', type: 'vec3' },
  13409. { name: 'p2', type: 'vec3' },
  13410. { name: 'p3', type: 'vec3' }
  13411. ]
  13412. } );
  13413. /** @module TextureBicubic **/
  13414. // Mipped Bicubic Texture Filtering by N8
  13415. // https://www.shadertoy.com/view/Dl2SDW
  13416. const bC = 1.0 / 6.0;
  13417. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13418. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13419. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13420. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13421. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13422. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13423. // h0 and h1 are the two offset functions
  13424. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13425. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13426. const bicubic = ( textureNode, texelSize, lod ) => {
  13427. const uv = textureNode.uvNode;
  13428. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13429. const iuv = floor( uvScaled );
  13430. const fuv = fract( uvScaled );
  13431. const g0x = g0( fuv.x );
  13432. const g1x = g1( fuv.x );
  13433. const h0x = h0( fuv.x );
  13434. const h1x = h1( fuv.x );
  13435. const h0y = h0( fuv.y );
  13436. const h1y = h1( fuv.y );
  13437. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13438. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13439. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13440. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13441. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13442. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13443. return a.add( b );
  13444. };
  13445. /**
  13446. * Applies mipped bicubic texture filtering to the given texture node.
  13447. *
  13448. * @method
  13449. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13450. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13451. * @return {Node} The filtered texture sample.
  13452. */
  13453. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13454. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13455. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13456. const fLodSizeInv = div( 1.0, fLodSize );
  13457. const cLodSizeInv = div( 1.0, cLodSize );
  13458. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13459. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13460. return fract( lodNode ).mix( fSample, cSample );
  13461. } );
  13462. //
  13463. // Transmission
  13464. //
  13465. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13466. // Direction of refracted light.
  13467. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13468. // Compute rotation-independent scaling of the model matrix.
  13469. const modelScale = vec3(
  13470. length( modelMatrix[ 0 ].xyz ),
  13471. length( modelMatrix[ 1 ].xyz ),
  13472. length( modelMatrix[ 2 ].xyz )
  13473. );
  13474. // The thickness is specified in local space.
  13475. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13476. } ).setLayout( {
  13477. name: 'getVolumeTransmissionRay',
  13478. type: 'vec3',
  13479. inputs: [
  13480. { name: 'n', type: 'vec3' },
  13481. { name: 'v', type: 'vec3' },
  13482. { name: 'thickness', type: 'float' },
  13483. { name: 'ior', type: 'float' },
  13484. { name: 'modelMatrix', type: 'mat4' }
  13485. ]
  13486. } );
  13487. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13488. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13489. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13490. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13491. } ).setLayout( {
  13492. name: 'applyIorToRoughness',
  13493. type: 'float',
  13494. inputs: [
  13495. { name: 'roughness', type: 'float' },
  13496. { name: 'ior', type: 'float' }
  13497. ]
  13498. } );
  13499. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13500. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13501. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13502. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13503. const transmissionSample = vTexture.sample( fragCoord );
  13504. //const transmissionSample = viewportMipTexture( fragCoord );
  13505. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13506. return textureBicubic( transmissionSample, lod );
  13507. } );
  13508. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13509. If( attenuationDistance.notEqual( 0 ), () => {
  13510. // Compute light attenuation using Beer's law.
  13511. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13512. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13513. return transmittance;
  13514. } );
  13515. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13516. return vec3( 1.0 );
  13517. } ).setLayout( {
  13518. name: 'volumeAttenuation',
  13519. type: 'vec3',
  13520. inputs: [
  13521. { name: 'transmissionDistance', type: 'float' },
  13522. { name: 'attenuationColor', type: 'vec3' },
  13523. { name: 'attenuationDistance', type: 'float' }
  13524. ]
  13525. } );
  13526. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13527. let transmittedLight, transmittance;
  13528. if ( dispersion ) {
  13529. transmittedLight = vec4().toVar();
  13530. transmittance = vec3().toVar();
  13531. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13532. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13533. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13534. const ior = iors.element( i );
  13535. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13536. const refractedRayExit = position.add( transmissionRay );
  13537. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13538. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13539. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13540. refractionCoords.addAssign( 1.0 );
  13541. refractionCoords.divAssign( 2.0 );
  13542. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13543. // Sample framebuffer to get pixel the refracted ray hits.
  13544. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13545. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13546. transmittedLight.a.addAssign( transmissionSample.a );
  13547. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13548. } );
  13549. transmittedLight.a.divAssign( 3.0 );
  13550. } else {
  13551. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13552. const refractedRayExit = position.add( transmissionRay );
  13553. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13554. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13555. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13556. refractionCoords.addAssign( 1.0 );
  13557. refractionCoords.divAssign( 2.0 );
  13558. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13559. // Sample framebuffer to get pixel the refracted ray hits.
  13560. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13561. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13562. }
  13563. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13564. const dotNV = n.dot( v ).clamp();
  13565. // Get the specular component.
  13566. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13567. dotNV,
  13568. specularColor,
  13569. specularF90,
  13570. roughness
  13571. } ) );
  13572. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13573. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13574. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13575. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13576. } );
  13577. //
  13578. // Iridescence
  13579. //
  13580. // XYZ to linear-sRGB color space
  13581. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13582. 3.2404542, -0.969266, 0.0556434,
  13583. -1.5371385, 1.8760108, -0.2040259,
  13584. -0.4985314, 0.0415560, 1.0572252
  13585. );
  13586. // Assume air interface for top
  13587. // Note: We don't handle the case fresnel0 == 1
  13588. const Fresnel0ToIor = ( fresnel0 ) => {
  13589. const sqrtF0 = fresnel0.sqrt();
  13590. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13591. };
  13592. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13593. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13594. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13595. };
  13596. // Fresnel equations for dielectric/dielectric interfaces.
  13597. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13598. // Evaluation XYZ sensitivity curves in Fourier space
  13599. const evalSensitivity = ( OPD, shift ) => {
  13600. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13601. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13602. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13603. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13604. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( -45282e5 ).exp() );
  13605. 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() );
  13606. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13607. const rgb = XYZ_TO_REC709.mul( xyz );
  13608. return rgb;
  13609. };
  13610. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13611. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13612. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13613. // Evaluate the cosTheta on the base layer (Snell law)
  13614. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13615. // Handle TIR:
  13616. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13617. If( cosTheta2Sq.lessThan( 0 ), () => {
  13618. return vec3( 1.0 );
  13619. } );
  13620. const cosTheta2 = cosTheta2Sq.sqrt();
  13621. // First interface
  13622. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13623. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13624. //const R21 = R12;
  13625. const T121 = R12.oneMinus();
  13626. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13627. const phi21 = float( Math.PI ).sub( phi12 );
  13628. // Second interface
  13629. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13630. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13631. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13632. const phi23 = vec3(
  13633. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13634. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13635. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13636. );
  13637. // Phase shift
  13638. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13639. const phi = vec3( phi21 ).add( phi23 );
  13640. // Compound terms
  13641. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13642. const r123 = R123.sqrt();
  13643. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13644. // Reflectance term for m = 0 (DC term amplitude)
  13645. const C0 = R12.add( Rs );
  13646. const I = C0.toVar();
  13647. // Reflectance term for m > 0 (pairs of diracs)
  13648. const Cm = Rs.sub( T121 ).toVar();
  13649. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13650. Cm.mulAssign( r123 );
  13651. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13652. I.addAssign( Cm.mul( Sm ) );
  13653. } );
  13654. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13655. return I.max( vec3( 0.0 ) );
  13656. } ).setLayout( {
  13657. name: 'evalIridescence',
  13658. type: 'vec3',
  13659. inputs: [
  13660. { name: 'outsideIOR', type: 'float' },
  13661. { name: 'eta2', type: 'float' },
  13662. { name: 'cosTheta1', type: 'float' },
  13663. { name: 'thinFilmThickness', type: 'float' },
  13664. { name: 'baseF0', type: 'vec3' }
  13665. ]
  13666. } );
  13667. //
  13668. // Sheen
  13669. //
  13670. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13671. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13672. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13673. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13674. const dotNV = normal.dot( viewDir ).saturate();
  13675. const r2 = roughness.pow2();
  13676. const a = select(
  13677. roughness.lessThan( 0.25 ),
  13678. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13679. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13680. );
  13681. const b = select(
  13682. roughness.lessThan( 0.25 ),
  13683. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13684. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13685. );
  13686. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13687. return DG.mul( 1.0 / Math.PI ).saturate();
  13688. } );
  13689. const clearcoatF0 = vec3( 0.04 );
  13690. const clearcoatF90 = float( 1 );
  13691. /**
  13692. * Represents the lighting model for a PBR material.
  13693. *
  13694. * @augments LightingModel
  13695. */
  13696. class PhysicalLightingModel extends LightingModel {
  13697. /**
  13698. * Constructs a new physical lighting model.
  13699. *
  13700. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13701. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13702. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13703. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13704. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13705. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13706. */
  13707. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13708. super();
  13709. /**
  13710. * Whether clearcoat is supported or not.
  13711. *
  13712. * @type {Boolean}
  13713. * @default false
  13714. */
  13715. this.clearcoat = clearcoat;
  13716. /**
  13717. * Whether sheen is supported or not.
  13718. *
  13719. * @type {Boolean}
  13720. * @default false
  13721. */
  13722. this.sheen = sheen;
  13723. /**
  13724. * Whether iridescence is supported or not.
  13725. *
  13726. * @type {Boolean}
  13727. * @default false
  13728. */
  13729. this.iridescence = iridescence;
  13730. /**
  13731. * Whether anisotropy is supported or not.
  13732. *
  13733. * @type {Boolean}
  13734. * @default false
  13735. */
  13736. this.anisotropy = anisotropy;
  13737. /**
  13738. * Whether transmission is supported or not.
  13739. *
  13740. * @type {Boolean}
  13741. * @default false
  13742. */
  13743. this.transmission = transmission;
  13744. /**
  13745. * Whether dispersion is supported or not.
  13746. *
  13747. * @type {Boolean}
  13748. * @default false
  13749. */
  13750. this.dispersion = dispersion;
  13751. /**
  13752. * The clear coat radiance.
  13753. *
  13754. * @type {Node?}
  13755. * @default null
  13756. */
  13757. this.clearcoatRadiance = null;
  13758. /**
  13759. * The clear coat specular direct.
  13760. *
  13761. * @type {Node?}
  13762. * @default null
  13763. */
  13764. this.clearcoatSpecularDirect = null;
  13765. /**
  13766. * The clear coat specular indirect.
  13767. *
  13768. * @type {Node?}
  13769. * @default null
  13770. */
  13771. this.clearcoatSpecularIndirect = null;
  13772. /**
  13773. * The sheen specular direct.
  13774. *
  13775. * @type {Node?}
  13776. * @default null
  13777. */
  13778. this.sheenSpecularDirect = null;
  13779. /**
  13780. * The sheen specular indirect.
  13781. *
  13782. * @type {Node?}
  13783. * @default null
  13784. */
  13785. this.sheenSpecularIndirect = null;
  13786. /**
  13787. * The iridescence Fresnel.
  13788. *
  13789. * @type {Node?}
  13790. * @default null
  13791. */
  13792. this.iridescenceFresnel = null;
  13793. /**
  13794. * The iridescence F0.
  13795. *
  13796. * @type {Node?}
  13797. * @default null
  13798. */
  13799. this.iridescenceF0 = null;
  13800. }
  13801. /**
  13802. * Depending on what features are requested, the method prepares certain node variables
  13803. * which are later used for lighting computations.
  13804. *
  13805. * @param {ContextNode} context - The current node context.
  13806. */
  13807. start( context ) {
  13808. if ( this.clearcoat === true ) {
  13809. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13810. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13811. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13812. }
  13813. if ( this.sheen === true ) {
  13814. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13815. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13816. }
  13817. if ( this.iridescence === true ) {
  13818. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13819. this.iridescenceFresnel = evalIridescence( {
  13820. outsideIOR: float( 1.0 ),
  13821. eta2: iridescenceIOR,
  13822. cosTheta1: dotNVi,
  13823. thinFilmThickness: iridescenceThickness,
  13824. baseF0: specularColor
  13825. } );
  13826. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13827. }
  13828. if ( this.transmission === true ) {
  13829. const position = positionWorld;
  13830. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13831. const n = transformedNormalWorld;
  13832. context.backdrop = getIBLVolumeRefraction(
  13833. n,
  13834. v,
  13835. roughness,
  13836. diffuseColor,
  13837. specularColor,
  13838. specularF90, // specularF90
  13839. position, // positionWorld
  13840. modelWorldMatrix, // modelMatrix
  13841. cameraViewMatrix, // viewMatrix
  13842. cameraProjectionMatrix, // projMatrix
  13843. ior,
  13844. thickness,
  13845. attenuationColor,
  13846. attenuationDistance,
  13847. this.dispersion ? dispersion : null
  13848. );
  13849. context.backdropAlpha = transmission;
  13850. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13851. }
  13852. }
  13853. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13854. // Approximates multi-scattering in order to preserve energy.
  13855. // http://www.jcgt.org/published/0008/01/03/
  13856. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13857. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13858. const fab = DFGApprox( { roughness, dotNV } );
  13859. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13860. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13861. const Ess = fab.x.add( fab.y );
  13862. const Ems = Ess.oneMinus();
  13863. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13864. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13865. singleScatter.addAssign( FssEss );
  13866. multiScatter.addAssign( Fms.mul( Ems ) );
  13867. }
  13868. /**
  13869. * Implements the direct light.
  13870. *
  13871. * @param {Object} input - The input data.
  13872. * @param {StackNode} stack - The current stack.
  13873. * @param {NodeBuilder} builder - The current node builder.
  13874. */
  13875. direct( { lightDirection, lightColor, reflectedLight } ) {
  13876. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13877. const irradiance = dotNL.mul( lightColor );
  13878. if ( this.sheen === true ) {
  13879. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13880. }
  13881. if ( this.clearcoat === true ) {
  13882. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13883. const ccIrradiance = dotNLcc.mul( lightColor );
  13884. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13885. }
  13886. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13887. 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 } ) ) );
  13888. }
  13889. /**
  13890. * This method is intended for implementing the direct light term for
  13891. * rect area light nodes.
  13892. *
  13893. * @param {Object} input - The input data.
  13894. * @param {StackNode} stack - The current stack.
  13895. * @param {NodeBuilder} builder - The current node builder.
  13896. */
  13897. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13898. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13899. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13900. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13901. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13902. const N = transformedNormalView;
  13903. const V = positionViewDirection;
  13904. const P = positionView.toVar();
  13905. const uv = LTC_Uv( { N, V, roughness } );
  13906. const t1 = ltc_1.sample( uv ).toVar();
  13907. const t2 = ltc_2.sample( uv ).toVar();
  13908. const mInv = mat3(
  13909. vec3( t1.x, 0, t1.y ),
  13910. vec3( 0, 1, 0 ),
  13911. vec3( t1.z, 0, t1.w )
  13912. ).toVar();
  13913. // LTC Fresnel Approximation by Stephen Hill
  13914. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13915. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13916. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13917. 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 } ) ) );
  13918. }
  13919. /**
  13920. * Implements the indirect lighting.
  13921. *
  13922. * @param {ContextNode} context - The current node context.
  13923. * @param {StackNode} stack - The current stack.
  13924. * @param {NodeBuilder} builder - The current node builder.
  13925. */
  13926. indirect( context, stack, builder ) {
  13927. this.indirectDiffuse( context, stack, builder );
  13928. this.indirectSpecular( context, stack, builder );
  13929. this.ambientOcclusion( context, stack, builder );
  13930. }
  13931. /**
  13932. * Implements the indirect diffuse term.
  13933. *
  13934. * @param {ContextNode} input - The current node context.
  13935. * @param {StackNode} stack - The current stack.
  13936. * @param {NodeBuilder} builder - The current node builder.
  13937. */
  13938. indirectDiffuse( { irradiance, reflectedLight } ) {
  13939. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13940. }
  13941. /**
  13942. * Implements the indirect specular term.
  13943. *
  13944. * @param {ContextNode} input - The current node context.
  13945. * @param {StackNode} stack - The current stack.
  13946. * @param {NodeBuilder} builder - The current node builder.
  13947. */
  13948. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13949. if ( this.sheen === true ) {
  13950. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13951. sheen,
  13952. IBLSheenBRDF( {
  13953. normal: transformedNormalView,
  13954. viewDir: positionViewDirection,
  13955. roughness: sheenRoughness
  13956. } )
  13957. ) );
  13958. }
  13959. if ( this.clearcoat === true ) {
  13960. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13961. const clearcoatEnv = EnvironmentBRDF( {
  13962. dotNV: dotNVcc,
  13963. specularColor: clearcoatF0,
  13964. specularF90: clearcoatF90,
  13965. roughness: clearcoatRoughness
  13966. } );
  13967. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13968. }
  13969. // Both indirect specular and indirect diffuse light accumulate here
  13970. const singleScattering = vec3().toVar( 'singleScattering' );
  13971. const multiScattering = vec3().toVar( 'multiScattering' );
  13972. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13973. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13974. const totalScattering = singleScattering.add( multiScattering );
  13975. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13976. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13977. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13978. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13979. }
  13980. /**
  13981. * Implements the ambient occlusion term.
  13982. *
  13983. * @param {ContextNode} input - The current node context.
  13984. * @param {StackNode} stack - The current stack.
  13985. * @param {NodeBuilder} builder - The current node builder.
  13986. */
  13987. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13988. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13989. const aoNV = dotNV.add( ambientOcclusion );
  13990. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  13991. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13992. if ( this.clearcoat === true ) {
  13993. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13994. }
  13995. if ( this.sheen === true ) {
  13996. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13997. }
  13998. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13999. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14000. }
  14001. /**
  14002. * Used for final lighting accumulations depending on the requested features.
  14003. *
  14004. * @param {ContextNode} context - The current node context.
  14005. * @param {StackNode} stack - The current stack.
  14006. * @param {NodeBuilder} builder - The current node builder.
  14007. */
  14008. finish( context ) {
  14009. const { outgoingLight } = context;
  14010. if ( this.clearcoat === true ) {
  14011. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14012. const Fcc = F_Schlick( {
  14013. dotVH: dotNVcc,
  14014. f0: clearcoatF0,
  14015. f90: clearcoatF90
  14016. } );
  14017. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14018. outgoingLight.assign( clearcoatLight );
  14019. }
  14020. if ( this.sheen === true ) {
  14021. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14022. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14023. outgoingLight.assign( sheenLight );
  14024. }
  14025. }
  14026. }
  14027. // These defines must match with PMREMGenerator
  14028. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14029. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14030. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14031. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14032. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14033. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14034. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14035. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14036. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14037. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14038. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14039. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14040. // These shader functions convert between the UV coordinates of a single face of
  14041. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14042. // sampling a textureCube (not generally normalized ).
  14043. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14044. const absDirection = vec3( abs( direction ) ).toVar();
  14045. const face = float( -1 ).toVar();
  14046. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14047. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14048. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14049. } ).Else( () => {
  14050. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14051. } );
  14052. } ).Else( () => {
  14053. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14054. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14055. } ).Else( () => {
  14056. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14057. } );
  14058. } );
  14059. return face;
  14060. } ).setLayout( {
  14061. name: 'getFace',
  14062. type: 'float',
  14063. inputs: [
  14064. { name: 'direction', type: 'vec3' }
  14065. ]
  14066. } );
  14067. // RH coordinate system; PMREM face-indexing convention
  14068. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14069. const uv = vec2().toVar();
  14070. If( face.equal( 0.0 ), () => {
  14071. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14072. } ).ElseIf( face.equal( 1.0 ), () => {
  14073. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14074. } ).ElseIf( face.equal( 2.0 ), () => {
  14075. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14076. } ).ElseIf( face.equal( 3.0 ), () => {
  14077. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14078. } ).ElseIf( face.equal( 4.0 ), () => {
  14079. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14080. } ).Else( () => {
  14081. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14082. } );
  14083. return mul( 0.5, uv.add( 1.0 ) );
  14084. } ).setLayout( {
  14085. name: 'getUV',
  14086. type: 'vec2',
  14087. inputs: [
  14088. { name: 'direction', type: 'vec3' },
  14089. { name: 'face', type: 'float' }
  14090. ]
  14091. } );
  14092. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14093. const mip = float( 0.0 ).toVar();
  14094. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14095. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14096. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14097. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14098. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14099. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14100. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14101. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14102. } ).Else( () => {
  14103. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14104. } );
  14105. return mip;
  14106. } ).setLayout( {
  14107. name: 'roughnessToMip',
  14108. type: 'float',
  14109. inputs: [
  14110. { name: 'roughness', type: 'float' }
  14111. ]
  14112. } );
  14113. // RH coordinate system; PMREM face-indexing convention
  14114. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14115. const uv = uv_immutable.toVar();
  14116. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14117. const direction = vec3( uv, 1.0 ).toVar();
  14118. If( face.equal( 0.0 ), () => {
  14119. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14120. } ).ElseIf( face.equal( 1.0 ), () => {
  14121. direction.assign( direction.xzy );
  14122. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14123. } ).ElseIf( face.equal( 2.0 ), () => {
  14124. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14125. } ).ElseIf( face.equal( 3.0 ), () => {
  14126. direction.assign( direction.zyx );
  14127. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14128. } ).ElseIf( face.equal( 4.0 ), () => {
  14129. direction.assign( direction.xzy );
  14130. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14131. } ).ElseIf( face.equal( 5.0 ), () => {
  14132. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14133. } );
  14134. return direction;
  14135. } ).setLayout( {
  14136. name: 'getDirection',
  14137. type: 'vec3',
  14138. inputs: [
  14139. { name: 'uv', type: 'vec2' },
  14140. { name: 'face', type: 'float' }
  14141. ]
  14142. } );
  14143. //
  14144. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14145. const roughness = float( roughness_immutable );
  14146. const sampleDir = vec3( sampleDir_immutable );
  14147. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14148. const mipF = fract( mip );
  14149. const mipInt = floor( mip );
  14150. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14151. If( mipF.notEqual( 0.0 ), () => {
  14152. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14153. color0.assign( mix( color0, color1, mipF ) );
  14154. } );
  14155. return color0;
  14156. } );
  14157. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14158. const mipInt = float( mipInt_immutable ).toVar();
  14159. const direction = vec3( direction_immutable );
  14160. const face = float( getFace( direction ) ).toVar();
  14161. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14162. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14163. const faceSize = float( exp2( mipInt ) ).toVar();
  14164. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14165. If( face.greaterThan( 2.0 ), () => {
  14166. uv.y.addAssign( faceSize );
  14167. face.subAssign( 3.0 );
  14168. } );
  14169. uv.x.addAssign( face.mul( faceSize ) );
  14170. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14171. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14172. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14173. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14174. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14175. } );
  14176. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14177. const cosTheta = cos( theta );
  14178. // Rodrigues' axis-angle rotation
  14179. const sampleDirection = outputDirection.mul( cosTheta )
  14180. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14181. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14182. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14183. } );
  14184. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14185. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14186. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14187. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14188. } );
  14189. axis.assign( normalize( axis ) );
  14190. const gl_FragColor = vec3().toVar();
  14191. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14192. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14193. If( i.greaterThanEqual( samples ), () => {
  14194. Break();
  14195. } );
  14196. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14197. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14198. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14199. } );
  14200. return vec4( gl_FragColor, 1 );
  14201. } );
  14202. /** @module PMREMNode **/
  14203. let _generator = null;
  14204. const _cache = new WeakMap();
  14205. /**
  14206. * Generates the cubeUV size based on the given image height.
  14207. *
  14208. * @private
  14209. * @param {Number} imageHeight - The image height.
  14210. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14211. */
  14212. function _generateCubeUVSize( imageHeight ) {
  14213. const maxMip = Math.log2( imageHeight ) - 2;
  14214. const texelHeight = 1.0 / imageHeight;
  14215. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14216. return { texelWidth, texelHeight, maxMip };
  14217. }
  14218. /**
  14219. * Generates a PMREM from the given texture .
  14220. *
  14221. * @private
  14222. * @param {Texture} texture - The texture to create the PMREM for.
  14223. * @return {Texture} The PMREM.
  14224. */
  14225. function _getPMREMFromTexture( texture ) {
  14226. let cacheTexture = _cache.get( texture );
  14227. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  14228. if ( pmremVersion !== texture.pmremVersion ) {
  14229. const image = texture.image;
  14230. if ( texture.isCubeTexture ) {
  14231. if ( isCubeMapReady( image ) ) {
  14232. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14233. } else {
  14234. return null;
  14235. }
  14236. } else {
  14237. if ( isEquirectangularMapReady( image ) ) {
  14238. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14239. } else {
  14240. return null;
  14241. }
  14242. }
  14243. cacheTexture.pmremVersion = texture.pmremVersion;
  14244. _cache.set( texture, cacheTexture );
  14245. }
  14246. return cacheTexture.texture;
  14247. }
  14248. /**
  14249. * This node represents a PMREM which is a special type of preprocessed
  14250. * environment map intended for PBR materials.
  14251. *
  14252. * ```js
  14253. * const material = new MeshStandardNodeMaterial();
  14254. * material.envNode = pmremTexture( envMap );
  14255. * ```
  14256. *
  14257. * @augments TempNode
  14258. */
  14259. class PMREMNode extends TempNode {
  14260. static get type() {
  14261. return 'PMREMNode';
  14262. }
  14263. /**
  14264. * Constructs a new function overloading node.
  14265. *
  14266. * @param {Texture} value - The input texture.
  14267. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14268. * @param {Node<float>} [levelNode=null] - The level node.
  14269. */
  14270. constructor( value, uvNode = null, levelNode = null ) {
  14271. super( 'vec3' );
  14272. /**
  14273. * Reference to the input texture.
  14274. *
  14275. * @private
  14276. * @type {Texture}
  14277. */
  14278. this._value = value;
  14279. /**
  14280. * Reference to the generated PMREM.
  14281. *
  14282. * @private
  14283. * @type {Texture | null}
  14284. * @default null
  14285. */
  14286. this._pmrem = null;
  14287. /**
  14288. * The uv node.
  14289. *
  14290. * @type {Node<vec2>}
  14291. */
  14292. this.uvNode = uvNode;
  14293. /**
  14294. * The level node.
  14295. *
  14296. * @type {Node<float>}
  14297. */
  14298. this.levelNode = levelNode;
  14299. /**
  14300. * Reference to a PMREM generator.
  14301. *
  14302. * @private
  14303. * @type {PMREMGenerator}
  14304. * @default null
  14305. */
  14306. this._generator = null;
  14307. const defaultTexture = new Texture();
  14308. defaultTexture.isRenderTargetTexture = true;
  14309. /**
  14310. * The texture node holding the generated PMREM.
  14311. *
  14312. * @private
  14313. * @type {TextureNode}
  14314. */
  14315. this._texture = texture( defaultTexture );
  14316. /**
  14317. * A uniform representing the PMREM's width.
  14318. *
  14319. * @private
  14320. * @type {UniformNode<float>}
  14321. */
  14322. this._width = uniform( 0 );
  14323. /**
  14324. * A uniform representing the PMREM's height.
  14325. *
  14326. * @private
  14327. * @type {UniformNode<float>}
  14328. */
  14329. this._height = uniform( 0 );
  14330. /**
  14331. * A uniform representing the PMREM's max Mip.
  14332. *
  14333. * @private
  14334. * @type {UniformNode<float>}
  14335. */
  14336. this._maxMip = uniform( 0 );
  14337. /**
  14338. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14339. *
  14340. * @type {String}
  14341. * @default 'render'
  14342. */
  14343. this.updateBeforeType = NodeUpdateType.RENDER;
  14344. }
  14345. set value( value ) {
  14346. this._value = value;
  14347. this._pmrem = null;
  14348. }
  14349. /**
  14350. * The node's texture value.
  14351. *
  14352. * @type {Texture}
  14353. */
  14354. get value() {
  14355. return this._value;
  14356. }
  14357. /**
  14358. * Uses the given PMREM texture to update internal values.
  14359. *
  14360. * @param {Texture} texture - The PMREM texture.
  14361. */
  14362. updateFromTexture( texture ) {
  14363. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14364. this._texture.value = texture;
  14365. this._width.value = cubeUVSize.texelWidth;
  14366. this._height.value = cubeUVSize.texelHeight;
  14367. this._maxMip.value = cubeUVSize.maxMip;
  14368. }
  14369. updateBefore() {
  14370. let pmrem = this._pmrem;
  14371. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  14372. const texture = this._value;
  14373. if ( pmremVersion !== texture.pmremVersion ) {
  14374. if ( texture.isPMREMTexture === true ) {
  14375. pmrem = texture;
  14376. } else {
  14377. pmrem = _getPMREMFromTexture( texture );
  14378. }
  14379. if ( pmrem !== null ) {
  14380. this._pmrem = pmrem;
  14381. this.updateFromTexture( pmrem );
  14382. }
  14383. }
  14384. }
  14385. setup( builder ) {
  14386. if ( _generator === null ) {
  14387. _generator = builder.createPMREMGenerator();
  14388. }
  14389. //
  14390. this.updateBefore( builder );
  14391. //
  14392. let uvNode = this.uvNode;
  14393. if ( uvNode === null && builder.context.getUV ) {
  14394. uvNode = builder.context.getUV( this );
  14395. }
  14396. //
  14397. const texture = this.value;
  14398. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14399. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14400. }
  14401. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14402. //
  14403. let levelNode = this.levelNode;
  14404. if ( levelNode === null && builder.context.getTextureLevel ) {
  14405. levelNode = builder.context.getTextureLevel( this );
  14406. }
  14407. //
  14408. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14409. }
  14410. }
  14411. /**
  14412. * Returns `true` if the given cube map image has been fully loaded.
  14413. *
  14414. * @private
  14415. * @param {Array<(Image|Object)>} image - The cube map image.
  14416. * @return {Boolean} Whether the given cube map is ready or not.
  14417. */
  14418. function isCubeMapReady( image ) {
  14419. if ( image === null || image === undefined ) return false;
  14420. let count = 0;
  14421. const length = 6;
  14422. for ( let i = 0; i < length; i ++ ) {
  14423. if ( image[ i ] !== undefined ) count ++;
  14424. }
  14425. return count === length;
  14426. }
  14427. /**
  14428. * Returns `true` if the given equirectangular image has been fully loaded.
  14429. *
  14430. * @private
  14431. * @param {(Image|Object)} image - The equirectangular image.
  14432. * @return {Boolean} Whether the given cube map is ready or not.
  14433. */
  14434. function isEquirectangularMapReady( image ) {
  14435. if ( image === null || image === undefined ) return false;
  14436. return image.height > 0;
  14437. }
  14438. /**
  14439. * TSL function for creating a PMREM node.
  14440. *
  14441. * @function
  14442. * @param {Texture} value - The input texture.
  14443. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14444. * @param {Node<float>} [levelNode=null] - The level node.
  14445. * @returns {PMREMNode}
  14446. */
  14447. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14448. const _envNodeCache = new WeakMap();
  14449. /**
  14450. * Represents a physical model for Image-based lighting (IBL). The environment
  14451. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14452. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14453. *
  14454. * @augments LightingNode
  14455. */
  14456. class EnvironmentNode extends LightingNode {
  14457. static get type() {
  14458. return 'EnvironmentNode';
  14459. }
  14460. /**
  14461. * Constructs a new environment node.
  14462. *
  14463. * @param {Node} [envNode=null] - A node representing the environment.
  14464. */
  14465. constructor( envNode = null ) {
  14466. super();
  14467. /**
  14468. * A node representing the environment.
  14469. *
  14470. * @type {Node?}
  14471. * @default null
  14472. */
  14473. this.envNode = envNode;
  14474. }
  14475. setup( builder ) {
  14476. const { material } = builder;
  14477. let envNode = this.envNode;
  14478. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14479. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14480. let cacheEnvNode = _envNodeCache.get( value );
  14481. if ( cacheEnvNode === undefined ) {
  14482. cacheEnvNode = pmremTexture( value );
  14483. _envNodeCache.set( value, cacheEnvNode );
  14484. }
  14485. envNode = cacheEnvNode;
  14486. }
  14487. //
  14488. const envMap = material.envMap;
  14489. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14490. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14491. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14492. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14493. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14494. const isolateRadiance = cache( radiance );
  14495. const isolateIrradiance = cache( irradiance );
  14496. //
  14497. builder.context.radiance.addAssign( isolateRadiance );
  14498. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14499. //
  14500. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14501. if ( clearcoatRadiance ) {
  14502. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14503. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14504. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14505. }
  14506. }
  14507. }
  14508. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14509. let reflectVec = null;
  14510. return {
  14511. getUV: () => {
  14512. if ( reflectVec === null ) {
  14513. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14514. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14515. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14516. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14517. }
  14518. return reflectVec;
  14519. },
  14520. getTextureLevel: () => {
  14521. return roughnessNode;
  14522. }
  14523. };
  14524. };
  14525. const createIrradianceContext = ( normalWorldNode ) => {
  14526. return {
  14527. getUV: () => {
  14528. return normalWorldNode;
  14529. },
  14530. getTextureLevel: () => {
  14531. return float( 1.0 );
  14532. }
  14533. };
  14534. };
  14535. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14536. /**
  14537. * Node material version of `MeshStandardMaterial`.
  14538. *
  14539. * @augments NodeMaterial
  14540. */
  14541. class MeshStandardNodeMaterial extends NodeMaterial {
  14542. static get type() {
  14543. return 'MeshStandardNodeMaterial';
  14544. }
  14545. /**
  14546. * Constructs a new mesh standard node material.
  14547. *
  14548. * @param {Object?} parameters - The configuration parameter.
  14549. */
  14550. constructor( parameters ) {
  14551. super();
  14552. /**
  14553. * This flag can be used for type testing.
  14554. *
  14555. * @type {Boolean}
  14556. * @readonly
  14557. * @default true
  14558. */
  14559. this.isMeshStandardNodeMaterial = true;
  14560. /**
  14561. * Set to `true` because standard materials react on lights.
  14562. *
  14563. * @type {Boolean}
  14564. * @default true
  14565. */
  14566. this.lights = true;
  14567. /**
  14568. * The emissive color of standard materials is by default inferred from the `emissive`,
  14569. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14570. * overwrite the default and define the emissive color with a node instead.
  14571. *
  14572. * If you don't want to overwrite the emissive color but modify the existing
  14573. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14574. *
  14575. * @type {Node<vec3>?}
  14576. * @default null
  14577. */
  14578. this.emissiveNode = null;
  14579. /**
  14580. * The metalness of standard materials is by default inferred from the `metalness`,
  14581. * and `metalnessMap` properties. This node property allows to
  14582. * overwrite the default and define the metalness with a node instead.
  14583. *
  14584. * If you don't want to overwrite the metalness but modify the existing
  14585. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14586. *
  14587. * @type {Node<float>?}
  14588. * @default null
  14589. */
  14590. this.metalnessNode = null;
  14591. /**
  14592. * The roughness of standard materials is by default inferred from the `roughness`,
  14593. * and `roughnessMap` properties. This node property allows to
  14594. * overwrite the default and define the roughness with a node instead.
  14595. *
  14596. * If you don't want to overwrite the roughness but modify the existing
  14597. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14598. *
  14599. * @type {Node<float>?}
  14600. * @default null
  14601. */
  14602. this.roughnessNode = null;
  14603. this.setDefaultValues( _defaultValues$6 );
  14604. this.setValues( parameters );
  14605. }
  14606. /**
  14607. * Overwritten since this type of material uses {@link EnvironmentNode}
  14608. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14609. * method honors `Scene.environment`.
  14610. *
  14611. * @param {NodeBuilder} builder - The current node builder.
  14612. * @return {EnvironmentNode<vec3>?} The environment node.
  14613. */
  14614. setupEnvironment( builder ) {
  14615. let envNode = super.setupEnvironment( builder );
  14616. if ( envNode === null && builder.environmentNode ) {
  14617. envNode = builder.environmentNode;
  14618. }
  14619. return envNode ? new EnvironmentNode( envNode ) : null;
  14620. }
  14621. /**
  14622. * Setups the lighting model.
  14623. *
  14624. * @return {PhysicalLightingModel} The lighting model.
  14625. */
  14626. setupLightingModel( /*builder*/ ) {
  14627. return new PhysicalLightingModel();
  14628. }
  14629. /**
  14630. * Setups the specular related node variables.
  14631. */
  14632. setupSpecular() {
  14633. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14634. specularColor.assign( specularColorNode );
  14635. specularF90.assign( 1.0 );
  14636. }
  14637. /**
  14638. * Setups the standard specific node variables.
  14639. *
  14640. * @param {NodeBuilder} builder - The current node builder.
  14641. */
  14642. setupVariants() {
  14643. // METALNESS
  14644. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14645. metalness.assign( metalnessNode );
  14646. // ROUGHNESS
  14647. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14648. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14649. roughness.assign( roughnessNode );
  14650. // SPECULAR COLOR
  14651. this.setupSpecular();
  14652. // DIFFUSE COLOR
  14653. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14654. }
  14655. copy( source ) {
  14656. this.emissiveNode = source.emissiveNode;
  14657. this.metalnessNode = source.metalnessNode;
  14658. this.roughnessNode = source.roughnessNode;
  14659. return super.copy( source );
  14660. }
  14661. }
  14662. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14663. /**
  14664. * Node material version of `MeshPhysicalMaterial`.
  14665. *
  14666. * @augments MeshStandardNodeMaterial
  14667. */
  14668. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14669. static get type() {
  14670. return 'MeshPhysicalNodeMaterial';
  14671. }
  14672. /**
  14673. * Constructs a new mesh physical node material.
  14674. *
  14675. * @param {Object?} parameters - The configuration parameter.
  14676. */
  14677. constructor( parameters ) {
  14678. super();
  14679. /**
  14680. * This flag can be used for type testing.
  14681. *
  14682. * @type {Boolean}
  14683. * @readonly
  14684. * @default true
  14685. */
  14686. this.isMeshPhysicalNodeMaterial = true;
  14687. /**
  14688. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14689. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14690. * and define the clearcoat with a node instead.
  14691. *
  14692. * If you don't want to overwrite the clearcoat but modify the existing
  14693. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14694. *
  14695. * @type {Node<float>?}
  14696. * @default null
  14697. */
  14698. this.clearcoatNode = null;
  14699. /**
  14700. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14701. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14702. * and define the clearcoat roughness with a node instead.
  14703. *
  14704. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14705. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14706. *
  14707. * @type {Node<float>?}
  14708. * @default null
  14709. */
  14710. this.clearcoatRoughnessNode = null;
  14711. /**
  14712. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14713. * property. This node property allows to overwrite the default
  14714. * and define the clearcoat normal with a node instead.
  14715. *
  14716. * If you don't want to overwrite the clearcoat normal but modify the existing
  14717. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14718. *
  14719. * @type {Node<vec3>?}
  14720. * @default null
  14721. */
  14722. this.clearcoatNormalNode = null;
  14723. /**
  14724. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14725. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14726. * and define the sheen with a node instead.
  14727. *
  14728. * If you don't want to overwrite the sheen but modify the existing
  14729. * value instead, use {@link module:MaterialNode.materialSheen}.
  14730. *
  14731. * @type {Node<vec3>?}
  14732. * @default null
  14733. */
  14734. this.sheenNode = null;
  14735. /**
  14736. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14737. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14738. * and define the sheen roughness with a node instead.
  14739. *
  14740. * If you don't want to overwrite the sheen roughness but modify the existing
  14741. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14742. *
  14743. * @type {Node<float>?}
  14744. * @default null
  14745. */
  14746. this.sheenRoughnessNode = null;
  14747. /**
  14748. * The iridescence of physical materials is by default inferred from the `iridescence`
  14749. * property. This node property allows to overwrite the default
  14750. * and define the iridescence with a node instead.
  14751. *
  14752. * If you don't want to overwrite the iridescence but modify the existing
  14753. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14754. *
  14755. * @type {Node<float>?}
  14756. * @default null
  14757. */
  14758. this.iridescenceNode = null;
  14759. /**
  14760. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14761. * property. This node property allows to overwrite the default
  14762. * and define the iridescence IOR with a node instead.
  14763. *
  14764. * If you don't want to overwrite the iridescence IOR but modify the existing
  14765. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14766. *
  14767. * @type {Node<float>?}
  14768. * @default null
  14769. */
  14770. this.iridescenceIORNode = null;
  14771. /**
  14772. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14773. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14774. * and define the iridescence thickness with a node instead.
  14775. *
  14776. * If you don't want to overwrite the iridescence thickness but modify the existing
  14777. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14778. *
  14779. * @type {Node<float>?}
  14780. * @default null
  14781. */
  14782. this.iridescenceThicknessNode = null;
  14783. /**
  14784. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14785. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14786. * and define the specular intensity with a node instead.
  14787. *
  14788. * If you don't want to overwrite the specular intensity but modify the existing
  14789. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14790. *
  14791. * @type {Node<float>?}
  14792. * @default null
  14793. */
  14794. this.specularIntensityNode = null;
  14795. /**
  14796. * The specular color of physical materials is by default inferred from the `specularColor`
  14797. * and `specularColorMap` properties. This node property allows to overwrite the default
  14798. * and define the specular color with a node instead.
  14799. *
  14800. * If you don't want to overwrite the specular color but modify the existing
  14801. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14802. *
  14803. * @type {Node<vec3>?}
  14804. * @default null
  14805. */
  14806. this.specularColorNode = null;
  14807. /**
  14808. * The ior of physical materials is by default inferred from the `ior`
  14809. * property. This node property allows to overwrite the default
  14810. * and define the ior with a node instead.
  14811. *
  14812. * If you don't want to overwrite the ior but modify the existing
  14813. * value instead, use {@link module:MaterialNode.materialIOR}.
  14814. *
  14815. * @type {Node<float>?}
  14816. * @default null
  14817. */
  14818. this.iorNode = null;
  14819. /**
  14820. * The transmission of physical materials is by default inferred from the `transmission` and
  14821. * `transmissionMap` properties. This node property allows to overwrite the default
  14822. * and define the transmission with a node instead.
  14823. *
  14824. * If you don't want to overwrite the transmission but modify the existing
  14825. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14826. *
  14827. * @type {Node<float>?}
  14828. * @default null
  14829. */
  14830. this.transmissionNode = null;
  14831. /**
  14832. * The thickness of physical materials is by default inferred from the `thickness` and
  14833. * `thicknessMap` properties. This node property allows to overwrite the default
  14834. * and define the thickness with a node instead.
  14835. *
  14836. * If you don't want to overwrite the thickness but modify the existing
  14837. * value instead, use {@link module:MaterialNode.materialThickness}.
  14838. *
  14839. * @type {Node<float>?}
  14840. * @default null
  14841. */
  14842. this.thicknessNode = null;
  14843. /**
  14844. * The attenuation distance of physical materials is by default inferred from the
  14845. * `attenuationDistance` property. This node property allows to overwrite the default
  14846. * and define the attenuation distance with a node instead.
  14847. *
  14848. * If you don't want to overwrite the attenuation distance but modify the existing
  14849. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14850. *
  14851. * @type {Node<float>?}
  14852. * @default null
  14853. */
  14854. this.attenuationDistanceNode = null;
  14855. /**
  14856. * The attenuation color of physical materials is by default inferred from the
  14857. * `attenuationColor` property. This node property allows to overwrite the default
  14858. * and define the attenuation color with a node instead.
  14859. *
  14860. * If you don't want to overwrite the attenuation color but modify the existing
  14861. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14862. *
  14863. * @type {Node<vec3>?}
  14864. * @default null
  14865. */
  14866. this.attenuationColorNode = null;
  14867. /**
  14868. * The dispersion of physical materials is by default inferred from the
  14869. * `dispersion` property. This node property allows to overwrite the default
  14870. * and define the dispersion with a node instead.
  14871. *
  14872. * If you don't want to overwrite the dispersion but modify the existing
  14873. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14874. *
  14875. * @type {Node<float>?}
  14876. * @default null
  14877. */
  14878. this.dispersionNode = null;
  14879. /**
  14880. * The anisotropy of physical materials is by default inferred from the
  14881. * `anisotropy` property. This node property allows to overwrite the default
  14882. * and define the anisotropy with a node instead.
  14883. *
  14884. * If you don't want to overwrite the anisotropy but modify the existing
  14885. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14886. *
  14887. * @type {Node<float>?}
  14888. * @default null
  14889. */
  14890. this.anisotropyNode = null;
  14891. this.setDefaultValues( _defaultValues$5 );
  14892. this.setValues( parameters );
  14893. }
  14894. /**
  14895. * Whether the lighting model should use clearcoat or not.
  14896. *
  14897. * @type {Boolean}
  14898. * @default true
  14899. */
  14900. get useClearcoat() {
  14901. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14902. }
  14903. /**
  14904. * Whether the lighting model should use iridescence or not.
  14905. *
  14906. * @type {Boolean}
  14907. * @default true
  14908. */
  14909. get useIridescence() {
  14910. return this.iridescence > 0 || this.iridescenceNode !== null;
  14911. }
  14912. /**
  14913. * Whether the lighting model should use sheen or not.
  14914. *
  14915. * @type {Boolean}
  14916. * @default true
  14917. */
  14918. get useSheen() {
  14919. return this.sheen > 0 || this.sheenNode !== null;
  14920. }
  14921. /**
  14922. * Whether the lighting model should use anisotropy or not.
  14923. *
  14924. * @type {Boolean}
  14925. * @default true
  14926. */
  14927. get useAnisotropy() {
  14928. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14929. }
  14930. /**
  14931. * Whether the lighting model should use transmission or not.
  14932. *
  14933. * @type {Boolean}
  14934. * @default true
  14935. */
  14936. get useTransmission() {
  14937. return this.transmission > 0 || this.transmissionNode !== null;
  14938. }
  14939. /**
  14940. * Whether the lighting model should use dispersion or not.
  14941. *
  14942. * @type {Boolean}
  14943. * @default true
  14944. */
  14945. get useDispersion() {
  14946. return this.dispersion > 0 || this.dispersionNode !== null;
  14947. }
  14948. /**
  14949. * Setups the specular related node variables.
  14950. */
  14951. setupSpecular() {
  14952. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14953. ior.assign( iorNode );
  14954. 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 ) );
  14955. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14956. }
  14957. /**
  14958. * Setups the lighting model.
  14959. *
  14960. * @return {PhysicalLightingModel} The lighting model.
  14961. */
  14962. setupLightingModel( /*builder*/ ) {
  14963. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14964. }
  14965. /**
  14966. * Setups the physical specific node variables.
  14967. *
  14968. * @param {NodeBuilder} builder - The current node builder.
  14969. */
  14970. setupVariants( builder ) {
  14971. super.setupVariants( builder );
  14972. // CLEARCOAT
  14973. if ( this.useClearcoat ) {
  14974. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14975. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14976. clearcoat.assign( clearcoatNode );
  14977. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14978. }
  14979. // SHEEN
  14980. if ( this.useSheen ) {
  14981. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14982. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14983. sheen.assign( sheenNode );
  14984. sheenRoughness.assign( sheenRoughnessNode );
  14985. }
  14986. // IRIDESCENCE
  14987. if ( this.useIridescence ) {
  14988. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14989. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14990. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14991. iridescence.assign( iridescenceNode );
  14992. iridescenceIOR.assign( iridescenceIORNode );
  14993. iridescenceThickness.assign( iridescenceThicknessNode );
  14994. }
  14995. // ANISOTROPY
  14996. if ( this.useAnisotropy ) {
  14997. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14998. anisotropy.assign( anisotropyV.length() );
  14999. If( anisotropy.equal( 0.0 ), () => {
  15000. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15001. } ).Else( () => {
  15002. anisotropyV.divAssign( vec2( anisotropy ) );
  15003. anisotropy.assign( anisotropy.saturate() );
  15004. } );
  15005. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15006. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15007. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15008. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15009. }
  15010. // TRANSMISSION
  15011. if ( this.useTransmission ) {
  15012. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15013. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15014. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15015. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15016. transmission.assign( transmissionNode );
  15017. thickness.assign( thicknessNode );
  15018. attenuationDistance.assign( attenuationDistanceNode );
  15019. attenuationColor.assign( attenuationColorNode );
  15020. if ( this.useDispersion ) {
  15021. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15022. dispersion.assign( dispersionNode );
  15023. }
  15024. }
  15025. }
  15026. /**
  15027. * Setups the clearcoat normal node.
  15028. *
  15029. * @return {Node<vec3>} The clearcoat normal.
  15030. */
  15031. setupClearcoatNormal() {
  15032. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15033. }
  15034. setup( builder ) {
  15035. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15036. super.setup( builder );
  15037. }
  15038. copy( source ) {
  15039. this.clearcoatNode = source.clearcoatNode;
  15040. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15041. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15042. this.sheenNode = source.sheenNode;
  15043. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15044. this.iridescenceNode = source.iridescenceNode;
  15045. this.iridescenceIORNode = source.iridescenceIORNode;
  15046. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15047. this.specularIntensityNode = source.specularIntensityNode;
  15048. this.specularColorNode = source.specularColorNode;
  15049. this.transmissionNode = source.transmissionNode;
  15050. this.thicknessNode = source.thicknessNode;
  15051. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15052. this.attenuationColorNode = source.attenuationColorNode;
  15053. this.dispersionNode = source.dispersionNode;
  15054. this.anisotropyNode = source.anisotropyNode;
  15055. return super.copy( source );
  15056. }
  15057. }
  15058. /** @module MeshSSSNodeMaterial **/
  15059. /**
  15060. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15061. *
  15062. * @augments PhysicalLightingModel
  15063. */
  15064. class SSSLightingModel extends PhysicalLightingModel {
  15065. /**
  15066. * Constructs a new physical lighting model.
  15067. *
  15068. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15069. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15070. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15071. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15072. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15073. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15074. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15075. */
  15076. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15077. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15078. /**
  15079. * Whether the lighting model should use SSS or not.
  15080. *
  15081. * @type {Boolean}
  15082. * @default false
  15083. */
  15084. this.useSSS = sss;
  15085. }
  15086. /**
  15087. * Extends the default implementation with a SSS term.
  15088. *
  15089. * 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/}
  15090. *
  15091. * @param {Object} input - The input data.
  15092. * @param {StackNode} stack - The current stack.
  15093. * @param {NodeBuilder} builder - The current node builder.
  15094. */
  15095. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15096. if ( this.useSSS === true ) {
  15097. const material = builder.material;
  15098. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15099. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15100. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15101. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15102. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15103. }
  15104. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15105. }
  15106. }
  15107. /**
  15108. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15109. * that implements a Subsurface scattering (SSS) term.
  15110. *
  15111. * @augments MeshPhysicalNodeMaterial
  15112. */
  15113. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15114. static get type() {
  15115. return 'MeshSSSNodeMaterial';
  15116. }
  15117. /**
  15118. * Constructs a new mesh SSS node material.
  15119. *
  15120. * @param {Object?} parameters - The configuration parameter.
  15121. */
  15122. constructor( parameters ) {
  15123. super( parameters );
  15124. /**
  15125. * Represents the thickness color.
  15126. *
  15127. * @type {Node<vec3>?}
  15128. * @default null
  15129. */
  15130. this.thicknessColorNode = null;
  15131. /**
  15132. * Represents the distortion factor.
  15133. *
  15134. * @type {Node<float>?}
  15135. */
  15136. this.thicknessDistortionNode = float( 0.1 );
  15137. /**
  15138. * Represents the thickness ambient factor.
  15139. *
  15140. * @type {Node<float>?}
  15141. */
  15142. this.thicknessAmbientNode = float( 0.0 );
  15143. /**
  15144. * Represents the thickness attenuation.
  15145. *
  15146. * @type {Node<float>?}
  15147. */
  15148. this.thicknessAttenuationNode = float( .1 );
  15149. /**
  15150. * Represents the thickness power.
  15151. *
  15152. * @type {Node<float>?}
  15153. */
  15154. this.thicknessPowerNode = float( 2.0 );
  15155. /**
  15156. * Represents the thickness scale.
  15157. *
  15158. * @type {Node<float>?}
  15159. */
  15160. this.thicknessScaleNode = float( 10.0 );
  15161. }
  15162. /**
  15163. * Whether the lighting model should use SSS or not.
  15164. *
  15165. * @type {Boolean}
  15166. * @default true
  15167. */
  15168. get useSSS() {
  15169. return this.thicknessColorNode !== null;
  15170. }
  15171. /**
  15172. * Setups the lighting model.
  15173. *
  15174. * @return {SSSLightingModel} The lighting model.
  15175. */
  15176. setupLightingModel( /*builder*/ ) {
  15177. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15178. }
  15179. copy( source ) {
  15180. this.thicknessColorNode = source.thicknessColorNode;
  15181. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15182. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15183. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15184. this.thicknessPowerNode = source.thicknessPowerNode;
  15185. this.thicknessScaleNode = source.thicknessScaleNode;
  15186. return super.copy( source );
  15187. }
  15188. }
  15189. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15190. // dotNL will be from -1.0 to 1.0
  15191. const dotNL = normal.dot( lightDirection );
  15192. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15193. if ( builder.material.gradientMap ) {
  15194. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15195. return vec3( gradientMap.r );
  15196. } else {
  15197. const fw = coord.fwidth().mul( 0.5 );
  15198. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15199. }
  15200. } );
  15201. /**
  15202. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15203. *
  15204. * @augments LightingModel
  15205. */
  15206. class ToonLightingModel extends LightingModel {
  15207. /**
  15208. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15209. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15210. *
  15211. * @param {Object} input - The input data.
  15212. * @param {StackNode} stack - The current stack.
  15213. * @param {NodeBuilder} builder - The current node builder.
  15214. */
  15215. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15216. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15217. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15218. }
  15219. /**
  15220. * Implements the indirect lighting.
  15221. *
  15222. * @param {ContextNode} input - The current node context.
  15223. * @param {StackNode} stack - The current stack.
  15224. * @param {NodeBuilder} builder - The current node builder.
  15225. */
  15226. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15227. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15228. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15229. }
  15230. }
  15231. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15232. /**
  15233. * Node material version of `MeshToonMaterial`.
  15234. *
  15235. * @augments NodeMaterial
  15236. */
  15237. class MeshToonNodeMaterial extends NodeMaterial {
  15238. static get type() {
  15239. return 'MeshToonNodeMaterial';
  15240. }
  15241. /**
  15242. * Constructs a new mesh toon node material.
  15243. *
  15244. * @param {Object?} parameters - The configuration parameter.
  15245. */
  15246. constructor( parameters ) {
  15247. super();
  15248. /**
  15249. * This flag can be used for type testing.
  15250. *
  15251. * @type {Boolean}
  15252. * @readonly
  15253. * @default true
  15254. */
  15255. this.isMeshToonNodeMaterial = true;
  15256. /**
  15257. * Set to `true` because toon materials react on lights.
  15258. *
  15259. * @type {Boolean}
  15260. * @default true
  15261. */
  15262. this.lights = true;
  15263. this.setDefaultValues( _defaultValues$4 );
  15264. this.setValues( parameters );
  15265. }
  15266. /**
  15267. * Setups the lighting model.
  15268. *
  15269. * @return {ToonLightingModel} The lighting model.
  15270. */
  15271. setupLightingModel( /*builder*/ ) {
  15272. return new ToonLightingModel();
  15273. }
  15274. }
  15275. /** @module MatcapUVNode **/
  15276. /**
  15277. * Can be used to compute texture coordinates for projecting a
  15278. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15279. *
  15280. * @augments TempNode
  15281. */
  15282. class MatcapUVNode extends TempNode {
  15283. static get type() {
  15284. return 'MatcapUVNode';
  15285. }
  15286. /**
  15287. * Constructs a new matcap uv node.
  15288. */
  15289. constructor() {
  15290. super( 'vec2' );
  15291. }
  15292. setup() {
  15293. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15294. const y = positionViewDirection.cross( x );
  15295. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15296. }
  15297. }
  15298. /**
  15299. * TSL function for creating a matcap uv node.
  15300. *
  15301. * @function
  15302. * @returns {MatcapUVNode}
  15303. */
  15304. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15305. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15306. /**
  15307. * Node material version of `MeshMatcapMaterial`.
  15308. *
  15309. * @augments NodeMaterial
  15310. */
  15311. class MeshMatcapNodeMaterial extends NodeMaterial {
  15312. static get type() {
  15313. return 'MeshMatcapNodeMaterial';
  15314. }
  15315. /**
  15316. * Constructs a new mesh normal node material.
  15317. *
  15318. * @param {Object?} parameters - The configuration parameter.
  15319. */
  15320. constructor( parameters ) {
  15321. super();
  15322. /**
  15323. * This flag can be used for type testing.
  15324. *
  15325. * @type {Boolean}
  15326. * @readonly
  15327. * @default true
  15328. */
  15329. this.isMeshMatcapNodeMaterial = true;
  15330. this.setDefaultValues( _defaultValues$3 );
  15331. this.setValues( parameters );
  15332. }
  15333. /**
  15334. * Setups the matcap specific node variables.
  15335. *
  15336. * @param {NodeBuilder} builder - The current node builder.
  15337. */
  15338. setupVariants( builder ) {
  15339. const uv = matcapUV;
  15340. let matcapColor;
  15341. if ( builder.material.matcap ) {
  15342. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15343. } else {
  15344. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15345. }
  15346. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15347. }
  15348. }
  15349. /** @module RotateNode **/
  15350. /**
  15351. * Applies a rotation to the given position node.
  15352. *
  15353. * @augments TempNode
  15354. */
  15355. class RotateNode extends TempNode {
  15356. static get type() {
  15357. return 'RotateNode';
  15358. }
  15359. /**
  15360. * Constructs a new rotate node.
  15361. *
  15362. * @param {Node} positionNode - The position node.
  15363. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15364. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15365. */
  15366. constructor( positionNode, rotationNode ) {
  15367. super();
  15368. /**
  15369. * The position node.
  15370. *
  15371. * @type {Node}
  15372. */
  15373. this.positionNode = positionNode;
  15374. /**
  15375. * Represents the rotation that is applied to the position node.
  15376. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15377. *
  15378. * @type {Node}
  15379. */
  15380. this.rotationNode = rotationNode;
  15381. }
  15382. /**
  15383. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15384. *
  15385. * @param {NodeBuilder} builder - The current node builder.
  15386. * @return {String} The node's type.
  15387. */
  15388. getNodeType( builder ) {
  15389. return this.positionNode.getNodeType( builder );
  15390. }
  15391. setup( builder ) {
  15392. const { rotationNode, positionNode } = this;
  15393. const nodeType = this.getNodeType( builder );
  15394. if ( nodeType === 'vec2' ) {
  15395. const cosAngle = rotationNode.cos();
  15396. const sinAngle = rotationNode.sin();
  15397. const rotationMatrix = mat2(
  15398. cosAngle, sinAngle,
  15399. sinAngle.negate(), cosAngle
  15400. );
  15401. return rotationMatrix.mul( positionNode );
  15402. } else {
  15403. const rotation = rotationNode;
  15404. 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 ) );
  15405. 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 ) );
  15406. 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 ) );
  15407. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15408. }
  15409. }
  15410. }
  15411. /**
  15412. * TSL function for creating a rotate node.
  15413. *
  15414. * @function
  15415. * @param {Node} positionNode - The position node.
  15416. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15417. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15418. * @returns {RotateNode}
  15419. */
  15420. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15421. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15422. /**
  15423. * Node material version of `SpriteMaterial`.
  15424. *
  15425. * @augments NodeMaterial
  15426. */
  15427. class SpriteNodeMaterial extends NodeMaterial {
  15428. static get type() {
  15429. return 'SpriteNodeMaterial';
  15430. }
  15431. /**
  15432. * Constructs a new sprite node material.
  15433. *
  15434. * @param {Object?} parameters - The configuration parameter.
  15435. */
  15436. constructor( parameters ) {
  15437. super();
  15438. /**
  15439. * This flag can be used for type testing.
  15440. *
  15441. * @type {Boolean}
  15442. * @readonly
  15443. * @default true
  15444. */
  15445. this.isSpriteNodeMaterial = true;
  15446. this._useSizeAttenuation = true;
  15447. /**
  15448. * This property makes it possible to define the position of the sprite with a
  15449. * node. That can be useful when the material is used with instanced rendering
  15450. * and node data are defined with an instanced attribute node:
  15451. * ```js
  15452. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15453. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15454. * ```
  15455. * Another possibility is to compute the instanced data with a compute shader:
  15456. * ```js
  15457. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15458. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15459. * ```
  15460. *
  15461. * @type {Node<vec2>?}
  15462. * @default null
  15463. */
  15464. this.positionNode = null;
  15465. /**
  15466. * The rotation of sprite materials is by default inferred from the `rotation`,
  15467. * property. This node property allows to overwrite the default and define
  15468. * the rotation with a node instead.
  15469. *
  15470. * If you don't want to overwrite the rotation but modify the existing
  15471. * value instead, use {@link module:MaterialNode.materialRotation}.
  15472. *
  15473. * @type {Node<float>?}
  15474. * @default null
  15475. */
  15476. this.rotationNode = null;
  15477. /**
  15478. * This node property provides an additional way to scale sprites next to
  15479. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15480. * is multiplied with the scale value of this node in the vertex shader.
  15481. *
  15482. * @type {Node<vec2>?}
  15483. * @default null
  15484. */
  15485. this.scaleNode = null;
  15486. this.setDefaultValues( _defaultValues$2 );
  15487. this.setValues( parameters );
  15488. }
  15489. /**
  15490. * Setups the position node in view space. This method implements
  15491. * the sprite specific vertex shader.
  15492. *
  15493. * @param {NodeBuilder} builder - The current node builder.
  15494. * @return {Node<vec3>} The position in view space.
  15495. */
  15496. setupPositionView( builder ) {
  15497. const { object, camera } = builder;
  15498. const sizeAttenuation = this.sizeAttenuation;
  15499. const { positionNode, rotationNode, scaleNode } = this;
  15500. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15501. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15502. if ( scaleNode !== null ) {
  15503. scale = scale.mul( float( scaleNode ) );
  15504. }
  15505. if ( sizeAttenuation === false ) {
  15506. if ( camera.isPerspectiveCamera ) {
  15507. scale = scale.mul( mvPosition.z.negate() );
  15508. } else {
  15509. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15510. scale = scale.mul( orthoScale.mul( 2 ) );
  15511. }
  15512. }
  15513. let alignedPosition = positionGeometry.xy;
  15514. if ( object.center && object.center.isVector2 === true ) {
  15515. const center = reference$1( 'center', 'vec2', object );
  15516. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15517. }
  15518. alignedPosition = alignedPosition.mul( scale );
  15519. const rotation = float( rotationNode || materialRotation );
  15520. const rotatedPosition = rotate( alignedPosition, rotation );
  15521. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15522. }
  15523. copy( source ) {
  15524. this.positionNode = source.positionNode;
  15525. this.rotationNode = source.rotationNode;
  15526. this.scaleNode = source.scaleNode;
  15527. return super.copy( source );
  15528. }
  15529. /**
  15530. * Whether to use size attenuation or not.
  15531. *
  15532. * @type {Boolean}
  15533. * @default true
  15534. */
  15535. get sizeAttenuation() {
  15536. return this._useSizeAttenuation;
  15537. }
  15538. set sizeAttenuation( value ) {
  15539. if ( this._useSizeAttenuation !== value ) {
  15540. this._useSizeAttenuation = value;
  15541. this.needsUpdate = true;
  15542. }
  15543. }
  15544. }
  15545. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15546. /**
  15547. * Node material version of `PointsMaterial`.
  15548. *
  15549. * @augments NodeMaterial
  15550. */
  15551. class PointsNodeMaterial extends SpriteNodeMaterial {
  15552. static get type() {
  15553. return 'PointsNodeMaterial';
  15554. }
  15555. /**
  15556. * Constructs a new points node material.
  15557. *
  15558. * @param {Object?} parameters - The configuration parameter.
  15559. */
  15560. constructor( parameters ) {
  15561. super();
  15562. /**
  15563. * This node property provides an additional way to set the point size.
  15564. *
  15565. * @type {Node<vec2>?}
  15566. * @default null
  15567. */
  15568. this.sizeNode = null;
  15569. /**
  15570. * This flag can be used for type testing.
  15571. *
  15572. * @type {Boolean}
  15573. * @readonly
  15574. * @default true
  15575. */
  15576. this.isPointsNodeMaterial = true;
  15577. this.setDefaultValues( _defaultValues$1 );
  15578. this.setValues( parameters );
  15579. }
  15580. setupPositionView() {
  15581. const { positionNode } = this;
  15582. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15583. }
  15584. setupVertex( builder ) {
  15585. const mvp = super.setupVertex( builder );
  15586. // skip further processing if the material is not a node material
  15587. if ( builder.material.isNodeMaterial !== true ) {
  15588. return mvp;
  15589. }
  15590. // ndc space
  15591. const { rotationNode, scaleNode, sizeNode } = this;
  15592. const alignedPosition = positionGeometry.xy.toVar();
  15593. const aspect = viewport.z.div( viewport.w );
  15594. // rotation
  15595. if ( rotationNode && rotationNode.isNode ) {
  15596. const rotation = float( rotationNode );
  15597. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15598. }
  15599. // point size
  15600. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15601. if ( this.sizeAttenuation === true ) {
  15602. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15603. }
  15604. // scale
  15605. if ( scaleNode && scaleNode.isNode ) {
  15606. pointSize = pointSize.mul( vec2( scaleNode ) );
  15607. }
  15608. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15609. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15610. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15611. // back to clip space
  15612. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15613. //clipPos.xy += offset;
  15614. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15615. return mvp;
  15616. }
  15617. /**
  15618. * Whether alpha to coverage should be used or not.
  15619. *
  15620. * @type {Boolean}
  15621. * @default true
  15622. */
  15623. get alphaToCoverage() {
  15624. return this._useAlphaToCoverage;
  15625. }
  15626. set alphaToCoverage( value ) {
  15627. if ( this._useAlphaToCoverage !== value ) {
  15628. this._useAlphaToCoverage = value;
  15629. this.needsUpdate = true;
  15630. }
  15631. }
  15632. }
  15633. /**
  15634. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15635. *
  15636. * @augments LightingModel
  15637. */
  15638. class ShadowMaskModel extends LightingModel {
  15639. /**
  15640. * Constructs a new shadow mask model.
  15641. */
  15642. constructor() {
  15643. super();
  15644. /**
  15645. * The shadow mask node.
  15646. *
  15647. * @type {Node}
  15648. */
  15649. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15650. }
  15651. /**
  15652. * Only used to save the shadow mask.
  15653. *
  15654. * @param {Object} input - The input data.
  15655. */
  15656. direct( { shadowMask } ) {
  15657. this.shadowNode.mulAssign( shadowMask );
  15658. }
  15659. /**
  15660. * Uses the shadow mask to produce the final color.
  15661. *
  15662. * @param {ContextNode} context - The current node context.
  15663. */
  15664. finish( context ) {
  15665. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15666. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15667. }
  15668. }
  15669. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15670. /**
  15671. * Node material version of `ShadowMaterial`.
  15672. *
  15673. * @augments NodeMaterial
  15674. */
  15675. class ShadowNodeMaterial extends NodeMaterial {
  15676. static get type() {
  15677. return 'ShadowNodeMaterial';
  15678. }
  15679. /**
  15680. * Constructs a new shadow node material.
  15681. *
  15682. * @param {Object?} parameters - The configuration parameter.
  15683. */
  15684. constructor( parameters ) {
  15685. super();
  15686. /**
  15687. * This flag can be used for type testing.
  15688. *
  15689. * @type {Boolean}
  15690. * @readonly
  15691. * @default true
  15692. */
  15693. this.isShadowNodeMaterial = true;
  15694. /**
  15695. * Set to `true` because so it's possible to implement
  15696. * the shadow mask effect.
  15697. *
  15698. * @type {Boolean}
  15699. * @default true
  15700. */
  15701. this.lights = true;
  15702. this.setDefaultValues( _defaultValues );
  15703. this.setValues( parameters );
  15704. }
  15705. /**
  15706. * Setups the lighting model.
  15707. *
  15708. * @return {ShadowMaskModel} The lighting model.
  15709. */
  15710. setupLightingModel( /*builder*/ ) {
  15711. return new ShadowMaskModel();
  15712. }
  15713. }
  15714. /** @module Texture3DNode **/
  15715. const normal = Fn( ( { texture, uv } ) => {
  15716. const epsilon = 0.0001;
  15717. const ret = vec3().toVar();
  15718. If( uv.x.lessThan( epsilon ), () => {
  15719. ret.assign( vec3( 1, 0, 0 ) );
  15720. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15721. ret.assign( vec3( 0, 1, 0 ) );
  15722. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15723. ret.assign( vec3( 0, 0, 1 ) );
  15724. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15725. ret.assign( vec3( -1, 0, 0 ) );
  15726. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15727. ret.assign( vec3( 0, -1, 0 ) );
  15728. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15729. ret.assign( vec3( 0, 0, -1 ) );
  15730. } ).Else( () => {
  15731. const step = 0.01;
  15732. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15733. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15734. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15735. ret.assign( vec3( x, y, z ) );
  15736. } );
  15737. return ret.normalize();
  15738. } );
  15739. /**
  15740. * This type of uniform node represents a 3D texture.
  15741. *
  15742. * @augments module:TextureNode~TextureNode
  15743. */
  15744. class Texture3DNode extends TextureNode {
  15745. static get type() {
  15746. return 'Texture3DNode';
  15747. }
  15748. /**
  15749. * Constructs a new 3D texture node.
  15750. *
  15751. * @param {Data3DTexture} value - The 3D texture.
  15752. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15753. * @param {Node<int>?} [levelNode=null] - The level node.
  15754. */
  15755. constructor( value, uvNode = null, levelNode = null ) {
  15756. super( value, uvNode, levelNode );
  15757. /**
  15758. * This flag can be used for type testing.
  15759. *
  15760. * @type {Boolean}
  15761. * @readonly
  15762. * @default true
  15763. */
  15764. this.isTexture3DNode = true;
  15765. }
  15766. /**
  15767. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15768. *
  15769. * @param {NodeBuilder} builder - The current node builder.
  15770. * @return {String} The input type.
  15771. */
  15772. getInputType( /*builder*/ ) {
  15773. return 'texture3D';
  15774. }
  15775. /**
  15776. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15777. * uv node.
  15778. *
  15779. * @return {Node<vec3>} The default uv node.
  15780. */
  15781. getDefaultUV() {
  15782. return vec3( 0.5, 0.5, 0.5 );
  15783. }
  15784. /**
  15785. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15786. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15787. *
  15788. * @param {Boolean} value - The update toggle.
  15789. */
  15790. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15791. /**
  15792. * Overwrites the default implementation to return the unmodified uv node.
  15793. *
  15794. * @param {NodeBuilder} builder - The current node builder.
  15795. * @param {Node} uvNode - The uv node to setup.
  15796. * @return {Node} The unmodified uv node.
  15797. */
  15798. setupUV( builder, uvNode ) {
  15799. const texture = this.value;
  15800. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15801. if ( this.sampler ) {
  15802. uvNode = uvNode.flipY();
  15803. } else {
  15804. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15805. }
  15806. }
  15807. return uvNode;
  15808. }
  15809. /**
  15810. * Generates the uv code snippet.
  15811. *
  15812. * @param {NodeBuilder} builder - The current node builder.
  15813. * @param {Node} uvNode - The uv node to generate code for.
  15814. * @return {String} The generated code snippet.
  15815. */
  15816. generateUV( builder, uvNode ) {
  15817. return uvNode.build( builder, 'vec3' );
  15818. }
  15819. /**
  15820. * TODO.
  15821. *
  15822. * @param {Node<vec3>} uvNode - The uv node .
  15823. * @return {Node<vec3>} TODO.
  15824. */
  15825. normal( uvNode ) {
  15826. return normal( { texture: this, uv: uvNode } );
  15827. }
  15828. }
  15829. /**
  15830. * TSL function for creating a 3D texture node.
  15831. *
  15832. * @function
  15833. * @param {Data3DTexture} value - The 3D texture.
  15834. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15835. * @param {Node<int>?} [levelNode=null] - The level node.
  15836. * @returns {Texture3DNode}
  15837. */
  15838. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15839. /** @module VolumeNodeMaterial **/
  15840. /**
  15841. * Node material intended for volume rendering. The volumetric data are
  15842. * defined with an instance of {@link Data3DTexture}.
  15843. *
  15844. * @augments NodeMaterial
  15845. */
  15846. class VolumeNodeMaterial extends NodeMaterial {
  15847. static get type() {
  15848. return 'VolumeNodeMaterial';
  15849. }
  15850. /**
  15851. * Constructs a new volume node material.
  15852. *
  15853. * @param {Object?} parameters - The configuration parameter.
  15854. */
  15855. constructor( parameters ) {
  15856. super();
  15857. /**
  15858. * This flag can be used for type testing.
  15859. *
  15860. * @type {Boolean}
  15861. * @readonly
  15862. * @default true
  15863. */
  15864. this.isVolumeNodeMaterial = true;
  15865. /**
  15866. * The base color of the volume.
  15867. *
  15868. * @type {Color}
  15869. * @default 100
  15870. */
  15871. this.base = new Color( 0xffffff );
  15872. /**
  15873. * A 3D data texture holding the volumetric data.
  15874. *
  15875. * @type {Data3DTexture?}
  15876. * @default null
  15877. */
  15878. this.map = null;
  15879. /**
  15880. * This number of samples for each ray that hits the mesh's surface
  15881. * and travels through the volume.
  15882. *
  15883. * @type {Number}
  15884. * @default 100
  15885. */
  15886. this.steps = 100;
  15887. /**
  15888. * Callback for {@link VolumeNodeMaterial#testNode}.
  15889. *
  15890. * @callback testNodeCallback
  15891. * @param {Data3DTexture<float>} map - The 3D texture.
  15892. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15893. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15894. * @param {Node<vec4>} finalColor - The final color.
  15895. */
  15896. /**
  15897. * The volume rendering of this material works by shooting rays
  15898. * from the camera position through each fragment of the mesh's
  15899. * surface and sample the inner volume in a raymarching fashion
  15900. * multiple times.
  15901. *
  15902. * This node can be used to assign a callback function of type `Fn`
  15903. * that will be executed per sample. The callback receives the
  15904. * texture, the sampled texture value as well as position on the surface
  15905. * where the rays enters the volume. The last parameter is a color
  15906. * that allows the callback to determine the final color.
  15907. *
  15908. * @type {testNodeCallback?}
  15909. * @default null
  15910. */
  15911. this.testNode = null;
  15912. this.setValues( parameters );
  15913. }
  15914. /**
  15915. * Setups the vertex and fragment stage of this node material.
  15916. *
  15917. * @param {NodeBuilder} builder - The current node builder.
  15918. */
  15919. setup( builder ) {
  15920. const map = texture3D( this.map, null, 0 );
  15921. const hitBox = Fn( ( { orig, dir } ) => {
  15922. const box_min = vec3( -0.5 );
  15923. const box_max = vec3( 0.5 );
  15924. const inv_dir = dir.reciprocal();
  15925. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15926. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15927. const tmin = min$1( tmin_tmp, tmax_tmp );
  15928. const tmax = max$1( tmin_tmp, tmax_tmp );
  15929. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15930. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15931. return vec2( t0, t1 );
  15932. } );
  15933. this.fragmentNode = Fn( () => {
  15934. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15935. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15936. const rayDir = vDirection.normalize();
  15937. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15938. bounds.x.greaterThan( bounds.y ).discard();
  15939. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15940. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15941. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15942. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15943. delta.divAssign( materialReference( 'steps', 'float' ) );
  15944. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15945. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15946. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15947. if ( this.testNode !== null ) {
  15948. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15949. } else {
  15950. // default to show surface of mesh
  15951. ac.a.assign( 1 );
  15952. Break();
  15953. }
  15954. p.addAssign( rayDir.mul( delta ) );
  15955. } );
  15956. ac.a.equal( 0 ).discard();
  15957. return vec4( ac );
  15958. } )();
  15959. super.setup( builder );
  15960. }
  15961. }
  15962. /**
  15963. * This module manages the internal animation loop of the renderer.
  15964. *
  15965. * @private
  15966. */
  15967. class Animation {
  15968. /**
  15969. * Constructs a new animation loop management component.
  15970. *
  15971. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15972. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15973. */
  15974. constructor( nodes, info ) {
  15975. /**
  15976. * Renderer component for managing nodes related logic.
  15977. *
  15978. * @type {Nodes}
  15979. */
  15980. this.nodes = nodes;
  15981. /**
  15982. * Renderer component for managing metrics and monitoring data.
  15983. *
  15984. * @type {Info}
  15985. */
  15986. this.info = info;
  15987. /**
  15988. * A reference to the context from `requestAnimationFrame()` can
  15989. * be called (usually `window`).
  15990. *
  15991. * @type {Window|XRSession}
  15992. */
  15993. this._context = self;
  15994. /**
  15995. * The user-defined animation loop.
  15996. *
  15997. * @type {Function?}
  15998. * @default null
  15999. */
  16000. this._animationLoop = null;
  16001. /**
  16002. * The requestId which is returned from the `requestAnimationFrame()` call.
  16003. * Can be used to cancel the stop the animation loop.
  16004. *
  16005. * @type {Number?}
  16006. * @default null
  16007. */
  16008. this._requestId = null;
  16009. }
  16010. /**
  16011. * Starts the internal animation loop.
  16012. */
  16013. start() {
  16014. const update = ( time, frame ) => {
  16015. this._requestId = this._context.requestAnimationFrame( update );
  16016. if ( this.info.autoReset === true ) this.info.reset();
  16017. this.nodes.nodeFrame.update();
  16018. this.info.frame = this.nodes.nodeFrame.frameId;
  16019. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16020. };
  16021. update();
  16022. }
  16023. /**
  16024. * Stops the internal animation loop.
  16025. */
  16026. stop() {
  16027. this._context.cancelAnimationFrame( this._requestId );
  16028. this._requestId = null;
  16029. }
  16030. /**
  16031. * Returns the user-level animation loop.
  16032. *
  16033. * @return {Function} The animation loop.
  16034. */
  16035. getAnimationLoop() {
  16036. return this._animationLoop;
  16037. }
  16038. /**
  16039. * Defines the user-level animation loop.
  16040. *
  16041. * @param {Function} callback - The animation loop.
  16042. */
  16043. setAnimationLoop( callback ) {
  16044. this._animationLoop = callback;
  16045. }
  16046. /**
  16047. * Returns the animation context.
  16048. *
  16049. * @return {Window|XRSession} The animation context.
  16050. */
  16051. getContext() {
  16052. return this._context;
  16053. }
  16054. /**
  16055. * Defines the context in which `requestAnimationFrame()` is executed.
  16056. *
  16057. * @param {Window|XRSession} context - The context to set.
  16058. */
  16059. setContext( context ) {
  16060. this._context = context;
  16061. }
  16062. /**
  16063. * Frees all internal resources and stops the animation loop.
  16064. */
  16065. dispose() {
  16066. this.stop();
  16067. }
  16068. }
  16069. /**
  16070. * Data structure for the renderer. It allows defining values
  16071. * with chained, hierarchical keys. Keys are meant to be
  16072. * objects since the module internally works with Weak Maps
  16073. * for performance reasons.
  16074. *
  16075. * @private
  16076. */
  16077. class ChainMap {
  16078. /**
  16079. * Constructs a new Chain Map.
  16080. */
  16081. constructor() {
  16082. /**
  16083. * The root Weak Map.
  16084. *
  16085. * @type {WeakMap}
  16086. */
  16087. this.weakMap = new WeakMap();
  16088. }
  16089. /**
  16090. * Returns the value for the given array of keys.
  16091. *
  16092. * @param {Array<Object>} keys - List of keys.
  16093. * @return {Any} The value. Returns `undefined` if no value was found.
  16094. */
  16095. get( keys ) {
  16096. let map = this.weakMap;
  16097. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16098. map = map.get( keys[ i ] );
  16099. if ( map === undefined ) return undefined;
  16100. }
  16101. return map.get( keys[ keys.length - 1 ] );
  16102. }
  16103. /**
  16104. * Sets the value for the given keys.
  16105. *
  16106. * @param {Array<Object>} keys - List of keys.
  16107. * @param {Any} value - The value to set.
  16108. * @return {ChainMap} A reference to this Chain Map.
  16109. */
  16110. set( keys, value ) {
  16111. let map = this.weakMap;
  16112. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16113. const key = keys[ i ];
  16114. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16115. map = map.get( key );
  16116. }
  16117. map.set( keys[ keys.length - 1 ], value );
  16118. return this;
  16119. }
  16120. /**
  16121. * Deletes a value for the given keys.
  16122. *
  16123. * @param {Array<Object>} keys - The keys.
  16124. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16125. */
  16126. delete( keys ) {
  16127. let map = this.weakMap;
  16128. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16129. map = map.get( keys[ i ] );
  16130. if ( map === undefined ) return false;
  16131. }
  16132. return map.delete( keys[ keys.length - 1 ] );
  16133. }
  16134. }
  16135. let _id$9 = 0;
  16136. function getKeys( obj ) {
  16137. const keys = Object.keys( obj );
  16138. let proto = Object.getPrototypeOf( obj );
  16139. while ( proto ) {
  16140. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16141. for ( const key in descriptors ) {
  16142. if ( descriptors[ key ] !== undefined ) {
  16143. const descriptor = descriptors[ key ];
  16144. if ( descriptor && typeof descriptor.get === 'function' ) {
  16145. keys.push( key );
  16146. }
  16147. }
  16148. }
  16149. proto = Object.getPrototypeOf( proto );
  16150. }
  16151. return keys;
  16152. }
  16153. /**
  16154. * A render object is the renderer's representation of single entity that gets drawn
  16155. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16156. * scene since render objects also depend from the used material, the current render context
  16157. * and the current scene's lighting.
  16158. *
  16159. * In general, the basic process of the renderer is:
  16160. *
  16161. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16162. * - Process the render lists by calling one or more render commands for each render item.
  16163. * - For each render command, request a render object and perform the draw.
  16164. *
  16165. * The module provides an interface to get data required for the draw command like the actual
  16166. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16167. * creating render objects should only be done when necessary.
  16168. *
  16169. * @private
  16170. */
  16171. class RenderObject {
  16172. /**
  16173. * Constructs a new render object.
  16174. *
  16175. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16176. * @param {Geometries} geometries - Renderer component for managing geometries.
  16177. * @param {Renderer} renderer - The renderer.
  16178. * @param {Object3D} object - The 3D object.
  16179. * @param {Material} material - The 3D object's material.
  16180. * @param {Scene} scene - The scene the 3D object belongs to.
  16181. * @param {Camera} camera - The camera the object should be rendered with.
  16182. * @param {LightsNode} lightsNode - The lights node.
  16183. * @param {RenderContext} renderContext - The render context.
  16184. * @param {ClippingContext} clippingContext - The clipping context.
  16185. */
  16186. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16187. this.id = _id$9 ++;
  16188. /**
  16189. * Renderer component for managing nodes related logic.
  16190. *
  16191. * @type {Nodes}
  16192. * @private
  16193. */
  16194. this._nodes = nodes;
  16195. /**
  16196. * Renderer component for managing geometries.
  16197. *
  16198. * @type {Geometries}
  16199. * @private
  16200. */
  16201. this._geometries = geometries;
  16202. /**
  16203. * The renderer.
  16204. *
  16205. * @type {Renderer}
  16206. */
  16207. this.renderer = renderer;
  16208. /**
  16209. * The 3D object.
  16210. *
  16211. * @type {Object3D}
  16212. */
  16213. this.object = object;
  16214. /**
  16215. * The 3D object's material.
  16216. *
  16217. * @type {Material}
  16218. */
  16219. this.material = material;
  16220. /**
  16221. * The scene the 3D object belongs to.
  16222. *
  16223. * @type {Scene}
  16224. */
  16225. this.scene = scene;
  16226. /**
  16227. * The camera the 3D object should be rendered with.
  16228. *
  16229. * @type {Camera}
  16230. */
  16231. this.camera = camera;
  16232. /**
  16233. * The lights node.
  16234. *
  16235. * @type {LightsNode}
  16236. */
  16237. this.lightsNode = lightsNode;
  16238. /**
  16239. * The render context.
  16240. *
  16241. * @type {RenderContext}
  16242. */
  16243. this.context = renderContext;
  16244. /**
  16245. * The 3D object's geometry.
  16246. *
  16247. * @type {BufferGeometry}
  16248. */
  16249. this.geometry = object.geometry;
  16250. /**
  16251. * The render object's version.
  16252. *
  16253. * @type {Number}
  16254. */
  16255. this.version = material.version;
  16256. /**
  16257. * The draw range of the geometry.
  16258. *
  16259. * @type {Object?}
  16260. * @default null
  16261. */
  16262. this.drawRange = null;
  16263. /**
  16264. * An array holding the buffer attributes
  16265. * of the render object. This entails attribute
  16266. * definitions on geometry and node level.
  16267. *
  16268. * @type {Array<BufferAttribute>?}
  16269. * @default null
  16270. */
  16271. this.attributes = null;
  16272. /**
  16273. * A reference to a render pipeline the render
  16274. * object is processed with.
  16275. *
  16276. * @type {RenderPipeline}
  16277. * @default null
  16278. */
  16279. this.pipeline = null;
  16280. /**
  16281. * Only relevant for objects using
  16282. * multiple materials. This represents a group entry
  16283. * from the respective `BufferGeometry`.
  16284. *
  16285. * @type {{start: Number, count: Number}?}
  16286. * @default null
  16287. */
  16288. this.group = null;
  16289. /**
  16290. * An array holding the vertex buffers which can
  16291. * be buffer attributes but also interleaved buffers.
  16292. *
  16293. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16294. * @default null
  16295. */
  16296. this.vertexBuffers = null;
  16297. /**
  16298. * The parameters for the draw command.
  16299. *
  16300. * @type {Object?}
  16301. * @default null
  16302. */
  16303. this.drawParams = null;
  16304. /**
  16305. * If this render object is used inside a render bundle,
  16306. * this property points to the respective bundle group.
  16307. *
  16308. * @type {BundleGroup?}
  16309. * @default null
  16310. */
  16311. this.bundle = null;
  16312. /**
  16313. * The clipping context.
  16314. *
  16315. * @type {ClippingContext}
  16316. */
  16317. this.clippingContext = clippingContext;
  16318. /**
  16319. * The clipping context's cache key.
  16320. *
  16321. * @type {String}
  16322. */
  16323. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16324. /**
  16325. * The initial node cache key.
  16326. *
  16327. * @type {Number}
  16328. */
  16329. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16330. /**
  16331. * The initial cache key.
  16332. *
  16333. * @type {Number}
  16334. */
  16335. this.initialCacheKey = this.getCacheKey();
  16336. /**
  16337. * The node builder state.
  16338. *
  16339. * @type {NodeBuilderState?}
  16340. * @private
  16341. * @default null
  16342. */
  16343. this._nodeBuilderState = null;
  16344. /**
  16345. * An array of bindings.
  16346. *
  16347. * @type {Array<BindGroup>?}
  16348. * @private
  16349. * @default null
  16350. */
  16351. this._bindings = null;
  16352. /**
  16353. * Reference to the node material observer.
  16354. *
  16355. * @type {NodeMaterialObserver?}
  16356. * @private
  16357. * @default null
  16358. */
  16359. this._monitor = null;
  16360. /**
  16361. * An event listener which is defined by `RenderObjects`. It performs
  16362. * clean up tasks when `dispose()` on this render object.
  16363. *
  16364. * @method
  16365. */
  16366. this.onDispose = null;
  16367. /**
  16368. * This flag can be used for type testing.
  16369. *
  16370. * @type {Boolean}
  16371. * @readonly
  16372. * @default true
  16373. */
  16374. this.isRenderObject = true;
  16375. /**
  16376. * An event listener which is executed when `dispose()` is called on
  16377. * the render object's material.
  16378. *
  16379. * @method
  16380. */
  16381. this.onMaterialDispose = () => {
  16382. this.dispose();
  16383. };
  16384. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16385. }
  16386. /**
  16387. * Updates the clipping context.
  16388. *
  16389. * @param {ClippingContext} context - The clipping context to set.
  16390. */
  16391. updateClipping( context ) {
  16392. this.clippingContext = context;
  16393. }
  16394. /**
  16395. * Whether the clipping requires an update or not.
  16396. *
  16397. * @type {Boolean}
  16398. * @readonly
  16399. */
  16400. get clippingNeedsUpdate() {
  16401. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16402. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16403. return true;
  16404. }
  16405. /**
  16406. * The number of clipping planes defined in context of hardware clipping.
  16407. *
  16408. * @type {Number}
  16409. * @readonly
  16410. */
  16411. get hardwareClippingPlanes() {
  16412. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16413. }
  16414. /**
  16415. * Returns the node builder state of this render object.
  16416. *
  16417. * @return {NodeBuilderState} The node builder state.
  16418. */
  16419. getNodeBuilderState() {
  16420. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16421. }
  16422. /**
  16423. * Returns the node material observer of this render object.
  16424. *
  16425. * @return {NodeMaterialObserver} The node material observer.
  16426. */
  16427. getMonitor() {
  16428. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16429. }
  16430. /**
  16431. * Returns an array of bind groups of this render object.
  16432. *
  16433. * @return {Array<BindGroup>} The bindings.
  16434. */
  16435. getBindings() {
  16436. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16437. }
  16438. /**
  16439. * Returns a binding group by group name of this render object.
  16440. *
  16441. * @param {String} name - The name of the binding group.
  16442. * @return {BindGroup?} The bindings.
  16443. */
  16444. getBindingGroup( name ) {
  16445. for ( const bindingGroup of this.getBindings() ) {
  16446. if ( bindingGroup.name === name ) {
  16447. return bindingGroup;
  16448. }
  16449. }
  16450. }
  16451. /**
  16452. * Returns the index of the render object's geometry.
  16453. *
  16454. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16455. */
  16456. getIndex() {
  16457. return this._geometries.getIndex( this );
  16458. }
  16459. /**
  16460. * Returns the indirect buffer attribute.
  16461. *
  16462. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16463. */
  16464. getIndirect() {
  16465. return this._geometries.getIndirect( this );
  16466. }
  16467. /**
  16468. * Returns an array that acts as a key for identifying the render object in a chain map.
  16469. *
  16470. * @return {Array<Object>} An array with object references.
  16471. */
  16472. getChainArray() {
  16473. return [ this.object, this.material, this.context, this.lightsNode ];
  16474. }
  16475. /**
  16476. * This method is used when the geometry of a 3D object has been exchanged and the
  16477. * respective render object now requires an update.
  16478. *
  16479. * @param {BufferGeometry} geometry - The geometry to set.
  16480. */
  16481. setGeometry( geometry ) {
  16482. this.geometry = geometry;
  16483. this.attributes = null;
  16484. }
  16485. /**
  16486. * Returns the buffer attributes of the render object. The returned array holds
  16487. * attribute definitions on geometry and node level.
  16488. *
  16489. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16490. */
  16491. getAttributes() {
  16492. if ( this.attributes !== null ) return this.attributes;
  16493. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16494. const geometry = this.geometry;
  16495. const attributes = [];
  16496. const vertexBuffers = new Set();
  16497. for ( const nodeAttribute of nodeAttributes ) {
  16498. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16499. if ( attribute === undefined ) continue;
  16500. attributes.push( attribute );
  16501. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16502. vertexBuffers.add( bufferAttribute );
  16503. }
  16504. this.attributes = attributes;
  16505. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16506. return attributes;
  16507. }
  16508. /**
  16509. * Returns the vertex buffers of the render object.
  16510. *
  16511. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16512. */
  16513. getVertexBuffers() {
  16514. if ( this.vertexBuffers === null ) this.getAttributes();
  16515. return this.vertexBuffers;
  16516. }
  16517. /**
  16518. * Returns the draw parameters for the render object.
  16519. *
  16520. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16521. */
  16522. getDrawParameters() {
  16523. const { object, material, geometry, group, drawRange } = this;
  16524. const drawParams = this.drawParams || ( this.drawParams = {
  16525. vertexCount: 0,
  16526. firstVertex: 0,
  16527. instanceCount: 0,
  16528. firstInstance: 0
  16529. } );
  16530. const index = this.getIndex();
  16531. const hasIndex = ( index !== null );
  16532. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16533. if ( instanceCount === 0 ) return null;
  16534. drawParams.instanceCount = instanceCount;
  16535. if ( object.isBatchedMesh === true ) return drawParams;
  16536. let rangeFactor = 1;
  16537. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16538. rangeFactor = 2;
  16539. }
  16540. let firstVertex = drawRange.start * rangeFactor;
  16541. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16542. if ( group !== null ) {
  16543. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16544. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16545. }
  16546. const position = geometry.attributes.position;
  16547. let itemCount = Infinity;
  16548. if ( hasIndex ) {
  16549. itemCount = index.count;
  16550. } else if ( position !== undefined && position !== null ) {
  16551. itemCount = position.count;
  16552. }
  16553. firstVertex = Math.max( firstVertex, 0 );
  16554. lastVertex = Math.min( lastVertex, itemCount );
  16555. const count = lastVertex - firstVertex;
  16556. if ( count < 0 || count === Infinity ) return null;
  16557. drawParams.vertexCount = count;
  16558. drawParams.firstVertex = firstVertex;
  16559. return drawParams;
  16560. }
  16561. /**
  16562. * Returns the render object's geometry cache key.
  16563. *
  16564. * The geometry cache key is part of the material cache key.
  16565. *
  16566. * @return {String} The geometry cache key.
  16567. */
  16568. getGeometryCacheKey() {
  16569. const { geometry } = this;
  16570. let cacheKey = '';
  16571. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16572. const attribute = geometry.attributes[ name ];
  16573. cacheKey += name + ',';
  16574. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16575. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16576. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16577. if ( attribute.normalized ) cacheKey += 'n,';
  16578. }
  16579. // structural equality isn't sufficient for morph targets since the
  16580. // data are maintained in textures. only if the targets are all equal
  16581. // the texture and thus the instance of `MorphNode` can be shared.
  16582. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16583. const targets = geometry.morphAttributes[ name ];
  16584. cacheKey += 'morph-' + name + ',';
  16585. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16586. const attribute = targets[ i ];
  16587. cacheKey += attribute.id + ',';
  16588. }
  16589. }
  16590. if ( geometry.index ) {
  16591. cacheKey += 'index,';
  16592. }
  16593. return cacheKey;
  16594. }
  16595. /**
  16596. * Returns the render object's material cache key.
  16597. *
  16598. * The material cache key is part of the render object cache key.
  16599. *
  16600. * @return {Number} The material cache key.
  16601. */
  16602. getMaterialCacheKey() {
  16603. const { object, material } = this;
  16604. let cacheKey = material.customProgramCacheKey();
  16605. for ( const property of getKeys( material ) ) {
  16606. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16607. const value = material[ property ];
  16608. let valueKey;
  16609. if ( value !== null ) {
  16610. // some material values require a formatting
  16611. const type = typeof value;
  16612. if ( type === 'number' ) {
  16613. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16614. } else if ( type === 'object' ) {
  16615. valueKey = '{';
  16616. if ( value.isTexture ) {
  16617. valueKey += value.mapping;
  16618. }
  16619. valueKey += '}';
  16620. } else {
  16621. valueKey = String( value );
  16622. }
  16623. } else {
  16624. valueKey = String( value );
  16625. }
  16626. cacheKey += /*property + ':' +*/ valueKey + ',';
  16627. }
  16628. cacheKey += this.clippingContextCacheKey + ',';
  16629. if ( object.geometry ) {
  16630. cacheKey += this.getGeometryCacheKey();
  16631. }
  16632. if ( object.skeleton ) {
  16633. cacheKey += object.skeleton.bones.length + ',';
  16634. }
  16635. if ( object.isBatchedMesh ) {
  16636. cacheKey += object._matricesTexture.uuid + ',';
  16637. if ( object._colorsTexture !== null ) {
  16638. cacheKey += object._colorsTexture.uuid + ',';
  16639. }
  16640. }
  16641. if ( object.count > 1 ) {
  16642. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16643. cacheKey += object.uuid + ',';
  16644. }
  16645. cacheKey += object.receiveShadow + ',';
  16646. return hashString( cacheKey );
  16647. }
  16648. /**
  16649. * Whether the geometry requires an update or not.
  16650. *
  16651. * @type {Boolean}
  16652. * @readonly
  16653. */
  16654. get needsGeometryUpdate() {
  16655. return this.geometry.id !== this.object.geometry.id;
  16656. }
  16657. /**
  16658. * Whether the render object requires an update or not.
  16659. *
  16660. * Note: There are two distinct places where render objects are checked for an update.
  16661. *
  16662. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16663. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16664. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16665. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16666. * a need for a refresh due to material, geometry or object related value changes.
  16667. *
  16668. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16669. * that performs the 'needsUpdate' check.
  16670. *
  16671. * @type {Boolean}
  16672. * @readonly
  16673. */
  16674. get needsUpdate() {
  16675. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16676. }
  16677. /**
  16678. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16679. *
  16680. * @return {Number} The cache key.
  16681. */
  16682. getDynamicCacheKey() {
  16683. let cacheKey = 0;
  16684. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16685. // the renderer is inside a shadow pass.
  16686. if ( this.material.isShadowPassMaterial !== true ) {
  16687. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16688. }
  16689. if ( this.camera.isArrayCamera ) {
  16690. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  16691. }
  16692. if ( this.object.receiveShadow ) {
  16693. cacheKey = hash$1( cacheKey, 1 );
  16694. }
  16695. return cacheKey;
  16696. }
  16697. /**
  16698. * Returns the render object's cache key.
  16699. *
  16700. * @return {Number} The cache key.
  16701. */
  16702. getCacheKey() {
  16703. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16704. }
  16705. /**
  16706. * Frees internal resources.
  16707. */
  16708. dispose() {
  16709. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16710. this.onDispose();
  16711. }
  16712. }
  16713. const _chainKeys$5 = [];
  16714. /**
  16715. * This module manages the render objects of the renderer.
  16716. *
  16717. * @private
  16718. */
  16719. class RenderObjects {
  16720. /**
  16721. * Constructs a new render object management component.
  16722. *
  16723. * @param {Renderer} renderer - The renderer.
  16724. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16725. * @param {Geometries} geometries - Renderer component for managing geometries.
  16726. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16727. * @param {Bindings} bindings - Renderer component for managing bindings.
  16728. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16729. */
  16730. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16731. /**
  16732. * The renderer.
  16733. *
  16734. * @type {Renderer}
  16735. */
  16736. this.renderer = renderer;
  16737. /**
  16738. * Renderer component for managing nodes related logic.
  16739. *
  16740. * @type {Nodes}
  16741. */
  16742. this.nodes = nodes;
  16743. /**
  16744. * Renderer component for managing geometries.
  16745. *
  16746. * @type {Geometries}
  16747. */
  16748. this.geometries = geometries;
  16749. /**
  16750. * Renderer component for managing pipelines.
  16751. *
  16752. * @type {Pipelines}
  16753. */
  16754. this.pipelines = pipelines;
  16755. /**
  16756. * Renderer component for managing bindings.
  16757. *
  16758. * @type {Bindings}
  16759. */
  16760. this.bindings = bindings;
  16761. /**
  16762. * Renderer component for managing metrics and monitoring data.
  16763. *
  16764. * @type {Info}
  16765. */
  16766. this.info = info;
  16767. /**
  16768. * A dictionary that manages render contexts in chain maps
  16769. * for each pass ID.
  16770. *
  16771. * @type {Object<String,ChainMap>}
  16772. */
  16773. this.chainMaps = {};
  16774. }
  16775. /**
  16776. * Returns a render object for the given object and state data.
  16777. *
  16778. * @param {Object3D} object - The 3D object.
  16779. * @param {Material} material - The 3D object's material.
  16780. * @param {Scene} scene - The scene the 3D object belongs to.
  16781. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16782. * @param {LightsNode} lightsNode - The lights node.
  16783. * @param {RenderContext} renderContext - The render context.
  16784. * @param {ClippingContext} clippingContext - The clipping context.
  16785. * @param {String?} passId - An optional ID for identifying the pass.
  16786. * @return {RenderObject} The render object.
  16787. */
  16788. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16789. const chainMap = this.getChainMap( passId );
  16790. // reuse chainArray
  16791. _chainKeys$5[ 0 ] = object;
  16792. _chainKeys$5[ 1 ] = material;
  16793. _chainKeys$5[ 2 ] = renderContext;
  16794. _chainKeys$5[ 3 ] = lightsNode;
  16795. let renderObject = chainMap.get( _chainKeys$5 );
  16796. if ( renderObject === undefined ) {
  16797. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16798. chainMap.set( _chainKeys$5, renderObject );
  16799. } else {
  16800. renderObject.updateClipping( clippingContext );
  16801. if ( renderObject.needsGeometryUpdate ) {
  16802. renderObject.setGeometry( object.geometry );
  16803. }
  16804. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16805. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16806. renderObject.dispose();
  16807. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16808. } else {
  16809. renderObject.version = material.version;
  16810. }
  16811. }
  16812. }
  16813. _chainKeys$5.length = 0;
  16814. return renderObject;
  16815. }
  16816. /**
  16817. * Returns a chain map for the given pass ID.
  16818. *
  16819. * @param {String} [passId='default'] - The pass ID.
  16820. * @return {ChainMap} The chain map.
  16821. */
  16822. getChainMap( passId = 'default' ) {
  16823. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16824. }
  16825. /**
  16826. * Frees internal resources.
  16827. */
  16828. dispose() {
  16829. this.chainMaps = {};
  16830. }
  16831. /**
  16832. * Factory method for creating render objects with the given list of parameters.
  16833. *
  16834. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16835. * @param {Geometries} geometries - Renderer component for managing geometries.
  16836. * @param {Renderer} renderer - The renderer.
  16837. * @param {Object3D} object - The 3D object.
  16838. * @param {Material} material - The object's material.
  16839. * @param {Scene} scene - The scene the 3D object belongs to.
  16840. * @param {Camera} camera - The camera the object should be rendered with.
  16841. * @param {LightsNode} lightsNode - The lights node.
  16842. * @param {RenderContext} renderContext - The render context.
  16843. * @param {ClippingContext} clippingContext - The clipping context.
  16844. * @param {String?} passId - An optional ID for identifying the pass.
  16845. * @return {RenderObject} The render object.
  16846. */
  16847. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16848. const chainMap = this.getChainMap( passId );
  16849. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16850. renderObject.onDispose = () => {
  16851. this.pipelines.delete( renderObject );
  16852. this.bindings.delete( renderObject );
  16853. this.nodes.delete( renderObject );
  16854. chainMap.delete( renderObject.getChainArray() );
  16855. };
  16856. return renderObject;
  16857. }
  16858. }
  16859. /**
  16860. * Data structure for the renderer. It is intended to manage
  16861. * data of objects in dictionaries.
  16862. *
  16863. * @private
  16864. */
  16865. class DataMap {
  16866. /**
  16867. * Constructs a new data map.
  16868. */
  16869. constructor() {
  16870. /**
  16871. * `DataMap` internally uses a weak map
  16872. * to manage its data.
  16873. *
  16874. * @type {WeakMap}
  16875. */
  16876. this.data = new WeakMap();
  16877. }
  16878. /**
  16879. * Returns the dictionary for the given object.
  16880. *
  16881. * @param {Object} object - The object.
  16882. * @return {Object} The dictionary.
  16883. */
  16884. get( object ) {
  16885. let map = this.data.get( object );
  16886. if ( map === undefined ) {
  16887. map = {};
  16888. this.data.set( object, map );
  16889. }
  16890. return map;
  16891. }
  16892. /**
  16893. * Deletes the dictionary for the given object.
  16894. *
  16895. * @param {Object} object - The object.
  16896. * @return {Object?} The deleted dictionary.
  16897. */
  16898. delete( object ) {
  16899. let map = null;
  16900. if ( this.data.has( object ) ) {
  16901. map = this.data.get( object );
  16902. this.data.delete( object );
  16903. }
  16904. return map;
  16905. }
  16906. /**
  16907. * Returns `true` if the given object has a dictionary defined.
  16908. *
  16909. * @param {Object} object - The object to test.
  16910. * @return {Boolean} Whether a dictionary is defined or not.
  16911. */
  16912. has( object ) {
  16913. return this.data.has( object );
  16914. }
  16915. /**
  16916. * Frees internal resources.
  16917. */
  16918. dispose() {
  16919. this.data = new WeakMap();
  16920. }
  16921. }
  16922. const AttributeType = {
  16923. VERTEX: 1,
  16924. INDEX: 2,
  16925. STORAGE: 3,
  16926. INDIRECT: 4
  16927. };
  16928. // size of a chunk in bytes (STD140 layout)
  16929. const GPU_CHUNK_BYTES = 16;
  16930. // @TODO: Move to src/constants.js
  16931. const BlendColorFactor = 211;
  16932. const OneMinusBlendColorFactor = 212;
  16933. /**
  16934. * This renderer module manages geometry attributes.
  16935. *
  16936. * @private
  16937. * @augments DataMap
  16938. */
  16939. class Attributes extends DataMap {
  16940. /**
  16941. * Constructs a new attribute management component.
  16942. *
  16943. * @param {Backend} backend - The renderer's backend.
  16944. */
  16945. constructor( backend ) {
  16946. super();
  16947. /**
  16948. * The renderer's backend.
  16949. *
  16950. * @type {Backend}
  16951. */
  16952. this.backend = backend;
  16953. }
  16954. /**
  16955. * Deletes the data for the given attribute.
  16956. *
  16957. * @param {BufferAttribute} attribute - The attribute.
  16958. * @return {Object} The deleted attribute data.
  16959. */
  16960. delete( attribute ) {
  16961. const attributeData = super.delete( attribute );
  16962. if ( attributeData !== undefined ) {
  16963. this.backend.destroyAttribute( attribute );
  16964. }
  16965. return attributeData;
  16966. }
  16967. /**
  16968. * Updates the given attribute. This method creates attribute buffers
  16969. * for new attributes and updates data for existing ones.
  16970. *
  16971. * @param {BufferAttribute} attribute - The attribute to update.
  16972. * @param {Number} type - The attribute type.
  16973. */
  16974. update( attribute, type ) {
  16975. const data = this.get( attribute );
  16976. if ( data.version === undefined ) {
  16977. if ( type === AttributeType.VERTEX ) {
  16978. this.backend.createAttribute( attribute );
  16979. } else if ( type === AttributeType.INDEX ) {
  16980. this.backend.createIndexAttribute( attribute );
  16981. } else if ( type === AttributeType.STORAGE ) {
  16982. this.backend.createStorageAttribute( attribute );
  16983. } else if ( type === AttributeType.INDIRECT ) {
  16984. this.backend.createIndirectStorageAttribute( attribute );
  16985. }
  16986. data.version = this._getBufferAttribute( attribute ).version;
  16987. } else {
  16988. const bufferAttribute = this._getBufferAttribute( attribute );
  16989. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16990. this.backend.updateAttribute( attribute );
  16991. data.version = bufferAttribute.version;
  16992. }
  16993. }
  16994. }
  16995. /**
  16996. * Utility method for handling interleaved buffer attributes correctly.
  16997. * To process them, their `InterleavedBuffer` is returned.
  16998. *
  16999. * @param {BufferAttribute} attribute - The attribute.
  17000. * @return {BufferAttribute|InterleavedBuffer}
  17001. */
  17002. _getBufferAttribute( attribute ) {
  17003. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17004. return attribute;
  17005. }
  17006. }
  17007. /**
  17008. * Returns `true` if the given array has values that require an Uint32 array type.
  17009. *
  17010. * @private
  17011. * @function
  17012. * @param {Array<Number>} array - The array to test.
  17013. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  17014. */
  17015. function arrayNeedsUint32( array ) {
  17016. // assumes larger values usually on last
  17017. for ( let i = array.length - 1; i >= 0; -- i ) {
  17018. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  17019. }
  17020. return false;
  17021. }
  17022. /**
  17023. * Returns the wireframe version for the given geometry.
  17024. *
  17025. * @private
  17026. * @function
  17027. * @param {BufferGeometry} geometry - The geometry.
  17028. * @return {Number} The version.
  17029. */
  17030. function getWireframeVersion( geometry ) {
  17031. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17032. }
  17033. /**
  17034. * Returns a wireframe index attribute for the given geometry.
  17035. *
  17036. * @private
  17037. * @function
  17038. * @param {BufferGeometry} geometry - The geometry.
  17039. * @return {BufferAttribute} The wireframe index attribute.
  17040. */
  17041. function getWireframeIndex( geometry ) {
  17042. const indices = [];
  17043. const geometryIndex = geometry.index;
  17044. const geometryPosition = geometry.attributes.position;
  17045. if ( geometryIndex !== null ) {
  17046. const array = geometryIndex.array;
  17047. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17048. const a = array[ i + 0 ];
  17049. const b = array[ i + 1 ];
  17050. const c = array[ i + 2 ];
  17051. indices.push( a, b, b, c, c, a );
  17052. }
  17053. } else {
  17054. const array = geometryPosition.array;
  17055. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17056. const a = i + 0;
  17057. const b = i + 1;
  17058. const c = i + 2;
  17059. indices.push( a, b, b, c, c, a );
  17060. }
  17061. }
  17062. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17063. attribute.version = getWireframeVersion( geometry );
  17064. return attribute;
  17065. }
  17066. /**
  17067. * This renderer module manages geometries.
  17068. *
  17069. * @private
  17070. * @augments DataMap
  17071. */
  17072. class Geometries extends DataMap {
  17073. /**
  17074. * Constructs a new geometry management component.
  17075. *
  17076. * @param {Attributes} attributes - Renderer component for managing attributes.
  17077. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17078. */
  17079. constructor( attributes, info ) {
  17080. super();
  17081. /**
  17082. * Renderer component for managing attributes.
  17083. *
  17084. * @type {Attributes}
  17085. */
  17086. this.attributes = attributes;
  17087. /**
  17088. * Renderer component for managing metrics and monitoring data.
  17089. *
  17090. * @type {Info}
  17091. */
  17092. this.info = info;
  17093. /**
  17094. * Weak Map for managing attributes for wireframe rendering.
  17095. *
  17096. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17097. */
  17098. this.wireframes = new WeakMap();
  17099. /**
  17100. * This Weak Map is used to make sure buffer attributes are
  17101. * updated only once per render call.
  17102. *
  17103. * @type {WeakMap<BufferAttribute,Number>}
  17104. */
  17105. this.attributeCall = new WeakMap();
  17106. }
  17107. /**
  17108. * Returns `true` if the given render object has an initialized geometry.
  17109. *
  17110. * @param {RenderObject} renderObject - The render object.
  17111. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17112. */
  17113. has( renderObject ) {
  17114. const geometry = renderObject.geometry;
  17115. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17116. }
  17117. /**
  17118. * Prepares the geometry of the given render object for rendering.
  17119. *
  17120. * @param {RenderObject} renderObject - The render object.
  17121. */
  17122. updateForRender( renderObject ) {
  17123. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17124. this.updateAttributes( renderObject );
  17125. }
  17126. /**
  17127. * Initializes the geometry of the given render object.
  17128. *
  17129. * @param {RenderObject} renderObject - The render object.
  17130. */
  17131. initGeometry( renderObject ) {
  17132. const geometry = renderObject.geometry;
  17133. const geometryData = this.get( geometry );
  17134. geometryData.initialized = true;
  17135. this.info.memory.geometries ++;
  17136. const onDispose = () => {
  17137. this.info.memory.geometries --;
  17138. const index = geometry.index;
  17139. const geometryAttributes = renderObject.getAttributes();
  17140. if ( index !== null ) {
  17141. this.attributes.delete( index );
  17142. }
  17143. for ( const geometryAttribute of geometryAttributes ) {
  17144. this.attributes.delete( geometryAttribute );
  17145. }
  17146. const wireframeAttribute = this.wireframes.get( geometry );
  17147. if ( wireframeAttribute !== undefined ) {
  17148. this.attributes.delete( wireframeAttribute );
  17149. }
  17150. geometry.removeEventListener( 'dispose', onDispose );
  17151. };
  17152. geometry.addEventListener( 'dispose', onDispose );
  17153. }
  17154. /**
  17155. * Updates the geometry attributes of the given render object.
  17156. *
  17157. * @param {RenderObject} renderObject - The render object.
  17158. */
  17159. updateAttributes( renderObject ) {
  17160. // attributes
  17161. const attributes = renderObject.getAttributes();
  17162. for ( const attribute of attributes ) {
  17163. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17164. this.updateAttribute( attribute, AttributeType.STORAGE );
  17165. } else {
  17166. this.updateAttribute( attribute, AttributeType.VERTEX );
  17167. }
  17168. }
  17169. // indexes
  17170. const index = this.getIndex( renderObject );
  17171. if ( index !== null ) {
  17172. this.updateAttribute( index, AttributeType.INDEX );
  17173. }
  17174. // indirect
  17175. const indirect = renderObject.geometry.indirect;
  17176. if ( indirect !== null ) {
  17177. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17178. }
  17179. }
  17180. /**
  17181. * Updates the given attribute.
  17182. *
  17183. * @param {BufferAttribute} attribute - The attribute to update.
  17184. * @param {Number} type - The attribute type.
  17185. */
  17186. updateAttribute( attribute, type ) {
  17187. const callId = this.info.render.calls;
  17188. if ( ! attribute.isInterleavedBufferAttribute ) {
  17189. if ( this.attributeCall.get( attribute ) !== callId ) {
  17190. this.attributes.update( attribute, type );
  17191. this.attributeCall.set( attribute, callId );
  17192. }
  17193. } else {
  17194. if ( this.attributeCall.get( attribute ) === undefined ) {
  17195. this.attributes.update( attribute, type );
  17196. this.attributeCall.set( attribute, callId );
  17197. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17198. this.attributes.update( attribute, type );
  17199. this.attributeCall.set( attribute.data, callId );
  17200. this.attributeCall.set( attribute, callId );
  17201. }
  17202. }
  17203. }
  17204. /**
  17205. * Returns the indirect buffer attribute of the given render object.
  17206. *
  17207. * @param {RenderObject} renderObject - The render object.
  17208. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17209. */
  17210. getIndirect( renderObject ) {
  17211. return renderObject.geometry.indirect;
  17212. }
  17213. /**
  17214. * Returns the index of the given render object's geometry. This is implemented
  17215. * in a method to return a wireframe index if necessary.
  17216. *
  17217. * @param {RenderObject} renderObject - The render object.
  17218. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17219. */
  17220. getIndex( renderObject ) {
  17221. const { geometry, material } = renderObject;
  17222. let index = geometry.index;
  17223. if ( material.wireframe === true ) {
  17224. const wireframes = this.wireframes;
  17225. let wireframeAttribute = wireframes.get( geometry );
  17226. if ( wireframeAttribute === undefined ) {
  17227. wireframeAttribute = getWireframeIndex( geometry );
  17228. wireframes.set( geometry, wireframeAttribute );
  17229. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17230. this.attributes.delete( wireframeAttribute );
  17231. wireframeAttribute = getWireframeIndex( geometry );
  17232. wireframes.set( geometry, wireframeAttribute );
  17233. }
  17234. index = wireframeAttribute;
  17235. }
  17236. return index;
  17237. }
  17238. }
  17239. /**
  17240. * This renderer module provides a series of statistical information
  17241. * about the GPU memory and the rendering process. Useful for debugging
  17242. * and monitoring.
  17243. */
  17244. class Info {
  17245. /**
  17246. * Constructs a new info component.
  17247. */
  17248. constructor() {
  17249. /**
  17250. * Whether frame related metrics should automatically
  17251. * be resetted or not. This property should be set to `false`
  17252. * by apps which manage their own animation loop. They must
  17253. * then call `renderer.info.reset()` once per frame manually.
  17254. *
  17255. * @type {Boolean}
  17256. * @default true
  17257. */
  17258. this.autoReset = true;
  17259. /**
  17260. * The current frame ID. This ID is managed
  17261. * by `NodeFrame`.
  17262. *
  17263. * @type {Number}
  17264. * @readonly
  17265. * @default 0
  17266. */
  17267. this.frame = 0;
  17268. /**
  17269. * The number of render calls since the
  17270. * app has been started.
  17271. *
  17272. * @type {Number}
  17273. * @readonly
  17274. * @default 0
  17275. */
  17276. this.calls = 0;
  17277. /**
  17278. * Render related metrics.
  17279. *
  17280. * @type {Object}
  17281. * @readonly
  17282. * @property {Number} calls - The number of render calls since the app has been started.
  17283. * @property {Number} frameCalls - The number of render calls of the current frame.
  17284. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17285. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17286. * @property {Number} points - The number of rendered point primitives of the current frame.
  17287. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17288. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17289. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17290. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17291. */
  17292. this.render = {
  17293. calls: 0,
  17294. frameCalls: 0,
  17295. drawCalls: 0,
  17296. triangles: 0,
  17297. points: 0,
  17298. lines: 0,
  17299. timestamp: 0,
  17300. previousFrameCalls: 0,
  17301. timestampCalls: 0
  17302. };
  17303. /**
  17304. * Compute related metrics.
  17305. *
  17306. * @type {Object}
  17307. * @readonly
  17308. * @property {Number} calls - The number of compute calls since the app has been started.
  17309. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17310. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17311. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17312. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17313. */
  17314. this.compute = {
  17315. calls: 0,
  17316. frameCalls: 0,
  17317. timestamp: 0,
  17318. previousFrameCalls: 0,
  17319. timestampCalls: 0
  17320. };
  17321. /**
  17322. * Memory related metrics.
  17323. *
  17324. * @type {Object}
  17325. * @readonly
  17326. * @property {Number} geometries - The number of active geometries.
  17327. * @property {Number} frameCalls - The number of active textures.
  17328. */
  17329. this.memory = {
  17330. geometries: 0,
  17331. textures: 0
  17332. };
  17333. }
  17334. /**
  17335. * This method should be executed per draw call and updates the corresponding metrics.
  17336. *
  17337. * @param {Object3D} object - The 3D object that is going to be rendered.
  17338. * @param {Number} count - The vertex or index count.
  17339. * @param {Number} instanceCount - The instance count.
  17340. */
  17341. update( object, count, instanceCount ) {
  17342. this.render.drawCalls ++;
  17343. if ( object.isMesh || object.isSprite ) {
  17344. this.render.triangles += instanceCount * ( count / 3 );
  17345. } else if ( object.isPoints ) {
  17346. this.render.points += instanceCount * count;
  17347. } else if ( object.isLineSegments ) {
  17348. this.render.lines += instanceCount * ( count / 2 );
  17349. } else if ( object.isLine ) {
  17350. this.render.lines += instanceCount * ( count - 1 );
  17351. } else {
  17352. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17353. }
  17354. }
  17355. /**
  17356. * Used by async render methods to updated timestamp metrics.
  17357. *
  17358. * @param {('render'|'compute')} type - The type of render call.
  17359. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17360. */
  17361. updateTimestamp( type, time ) {
  17362. if ( this[ type ].timestampCalls === 0 ) {
  17363. this[ type ].timestamp = 0;
  17364. }
  17365. this[ type ].timestamp += time;
  17366. this[ type ].timestampCalls ++;
  17367. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17368. this[ type ].timestampCalls = 0;
  17369. }
  17370. }
  17371. /**
  17372. * Resets frame related metrics.
  17373. */
  17374. reset() {
  17375. const previousRenderFrameCalls = this.render.frameCalls;
  17376. this.render.previousFrameCalls = previousRenderFrameCalls;
  17377. const previousComputeFrameCalls = this.compute.frameCalls;
  17378. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17379. this.render.drawCalls = 0;
  17380. this.render.frameCalls = 0;
  17381. this.compute.frameCalls = 0;
  17382. this.render.triangles = 0;
  17383. this.render.points = 0;
  17384. this.render.lines = 0;
  17385. }
  17386. /**
  17387. * Performs a complete reset of the object.
  17388. */
  17389. dispose() {
  17390. this.reset();
  17391. this.calls = 0;
  17392. this.render.calls = 0;
  17393. this.compute.calls = 0;
  17394. this.render.timestamp = 0;
  17395. this.compute.timestamp = 0;
  17396. this.memory.geometries = 0;
  17397. this.memory.textures = 0;
  17398. }
  17399. }
  17400. /**
  17401. * Abstract class for representing pipelines.
  17402. *
  17403. * @private
  17404. * @abstract
  17405. */
  17406. class Pipeline {
  17407. /**
  17408. * Constructs a new pipeline.
  17409. *
  17410. * @param {String} cacheKey - The pipeline's cache key.
  17411. */
  17412. constructor( cacheKey ) {
  17413. /**
  17414. * The pipeline's cache key.
  17415. *
  17416. * @type {String}
  17417. */
  17418. this.cacheKey = cacheKey;
  17419. /**
  17420. * How often the pipeline is currently in use.
  17421. *
  17422. * @type {Number}
  17423. * @default 0
  17424. */
  17425. this.usedTimes = 0;
  17426. }
  17427. }
  17428. /**
  17429. * Class for representing render pipelines.
  17430. *
  17431. * @private
  17432. * @augments Pipeline
  17433. */
  17434. class RenderPipeline extends Pipeline {
  17435. /**
  17436. * Constructs a new render pipeline.
  17437. *
  17438. * @param {String} cacheKey - The pipeline's cache key.
  17439. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17440. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17441. */
  17442. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17443. super( cacheKey );
  17444. /**
  17445. * The pipeline's vertex shader.
  17446. *
  17447. * @type {ProgrammableStage}
  17448. */
  17449. this.vertexProgram = vertexProgram;
  17450. /**
  17451. * The pipeline's fragment shader.
  17452. *
  17453. * @type {ProgrammableStage}
  17454. */
  17455. this.fragmentProgram = fragmentProgram;
  17456. }
  17457. }
  17458. /**
  17459. * Class for representing compute pipelines.
  17460. *
  17461. * @private
  17462. * @augments Pipeline
  17463. */
  17464. class ComputePipeline extends Pipeline {
  17465. /**
  17466. * Constructs a new render pipeline.
  17467. *
  17468. * @param {String} cacheKey - The pipeline's cache key.
  17469. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17470. */
  17471. constructor( cacheKey, computeProgram ) {
  17472. super( cacheKey );
  17473. /**
  17474. * The pipeline's compute shader.
  17475. *
  17476. * @type {ProgrammableStage}
  17477. */
  17478. this.computeProgram = computeProgram;
  17479. /**
  17480. * This flag can be used for type testing.
  17481. *
  17482. * @type {Boolean}
  17483. * @readonly
  17484. * @default true
  17485. */
  17486. this.isComputePipeline = true;
  17487. }
  17488. }
  17489. let _id$8 = 0;
  17490. /**
  17491. * Class for representing programmable stages which are vertex,
  17492. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17493. * they represent the programmable part of a pipeline.
  17494. *
  17495. * @private
  17496. */
  17497. class ProgrammableStage {
  17498. /**
  17499. * Constructs a new programmable stage.
  17500. *
  17501. * @param {String} code - The shader code.
  17502. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17503. * @param {String} name - The name of the shader.
  17504. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17505. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17506. */
  17507. constructor( code, stage, name, transforms = null, attributes = null ) {
  17508. /**
  17509. * The id of the programmable stage.
  17510. *
  17511. * @type {Number}
  17512. */
  17513. this.id = _id$8 ++;
  17514. /**
  17515. * The shader code.
  17516. *
  17517. * @type {String}
  17518. */
  17519. this.code = code;
  17520. /**
  17521. * The type of stage.
  17522. *
  17523. * @type {String}
  17524. */
  17525. this.stage = stage;
  17526. /**
  17527. * The name of the stage.
  17528. * This is used for debugging purposes.
  17529. *
  17530. * @type {String}
  17531. */
  17532. this.name = name;
  17533. /**
  17534. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17535. *
  17536. * @type {Array<Object>?}
  17537. */
  17538. this.transforms = transforms;
  17539. /**
  17540. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17541. *
  17542. * @type {Array<Object>?}
  17543. */
  17544. this.attributes = attributes;
  17545. /**
  17546. * How often the programmable stage is currently in use.
  17547. *
  17548. * @type {Number}
  17549. * @default 0
  17550. */
  17551. this.usedTimes = 0;
  17552. }
  17553. }
  17554. /**
  17555. * This renderer module manages the pipelines of the renderer.
  17556. *
  17557. * @private
  17558. * @augments DataMap
  17559. */
  17560. class Pipelines extends DataMap {
  17561. /**
  17562. * Constructs a new pipeline management component.
  17563. *
  17564. * @param {Backend} backend - The renderer's backend.
  17565. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17566. */
  17567. constructor( backend, nodes ) {
  17568. super();
  17569. /**
  17570. * The renderer's backend.
  17571. *
  17572. * @type {Backend}
  17573. */
  17574. this.backend = backend;
  17575. /**
  17576. * Renderer component for managing nodes related logic.
  17577. *
  17578. * @type {Nodes}
  17579. */
  17580. this.nodes = nodes;
  17581. /**
  17582. * A references to the bindings management component.
  17583. * This reference will be set inside the `Bindings`
  17584. * constructor.
  17585. *
  17586. * @type {Bindings?}
  17587. * @default null
  17588. */
  17589. this.bindings = null;
  17590. /**
  17591. * Internal cache for maintaining pipelines.
  17592. * The key of the map is a cache key, the value the pipeline.
  17593. *
  17594. * @type {Map<String,Pipeline>}
  17595. */
  17596. this.caches = new Map();
  17597. /**
  17598. * This dictionary maintains for each shader stage type (vertex,
  17599. * fragment and compute) the programmable stage objects which
  17600. * represent the actual shader code.
  17601. *
  17602. * @type {Object<String,Map>}
  17603. */
  17604. this.programs = {
  17605. vertex: new Map(),
  17606. fragment: new Map(),
  17607. compute: new Map()
  17608. };
  17609. }
  17610. /**
  17611. * Returns a compute pipeline for the given compute node.
  17612. *
  17613. * @param {Node} computeNode - The compute node.
  17614. * @param {Array<BindGroup>} bindings - The bindings.
  17615. * @return {ComputePipeline} The compute pipeline.
  17616. */
  17617. getForCompute( computeNode, bindings ) {
  17618. const { backend } = this;
  17619. const data = this.get( computeNode );
  17620. if ( this._needsComputeUpdate( computeNode ) ) {
  17621. const previousPipeline = data.pipeline;
  17622. if ( previousPipeline ) {
  17623. previousPipeline.usedTimes --;
  17624. previousPipeline.computeProgram.usedTimes --;
  17625. }
  17626. // get shader
  17627. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17628. // programmable stage
  17629. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17630. if ( stageCompute === undefined ) {
  17631. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17632. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17633. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17634. backend.createProgram( stageCompute );
  17635. }
  17636. // determine compute pipeline
  17637. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17638. let pipeline = this.caches.get( cacheKey );
  17639. if ( pipeline === undefined ) {
  17640. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17641. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17642. }
  17643. // keep track of all used times
  17644. pipeline.usedTimes ++;
  17645. stageCompute.usedTimes ++;
  17646. //
  17647. data.version = computeNode.version;
  17648. data.pipeline = pipeline;
  17649. }
  17650. return data.pipeline;
  17651. }
  17652. /**
  17653. * Returns a render pipeline for the given render object.
  17654. *
  17655. * @param {RenderObject} renderObject - The render object.
  17656. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17657. * @return {RenderPipeline} The render pipeline.
  17658. */
  17659. getForRender( renderObject, promises = null ) {
  17660. const { backend } = this;
  17661. const data = this.get( renderObject );
  17662. if ( this._needsRenderUpdate( renderObject ) ) {
  17663. const previousPipeline = data.pipeline;
  17664. if ( previousPipeline ) {
  17665. previousPipeline.usedTimes --;
  17666. previousPipeline.vertexProgram.usedTimes --;
  17667. previousPipeline.fragmentProgram.usedTimes --;
  17668. }
  17669. // get shader
  17670. const nodeBuilderState = renderObject.getNodeBuilderState();
  17671. const name = renderObject.material ? renderObject.material.name : '';
  17672. // programmable stages
  17673. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17674. if ( stageVertex === undefined ) {
  17675. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17676. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17677. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17678. backend.createProgram( stageVertex );
  17679. }
  17680. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17681. if ( stageFragment === undefined ) {
  17682. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17683. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17684. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17685. backend.createProgram( stageFragment );
  17686. }
  17687. // determine render pipeline
  17688. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17689. let pipeline = this.caches.get( cacheKey );
  17690. if ( pipeline === undefined ) {
  17691. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17692. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17693. } else {
  17694. renderObject.pipeline = pipeline;
  17695. }
  17696. // keep track of all used times
  17697. pipeline.usedTimes ++;
  17698. stageVertex.usedTimes ++;
  17699. stageFragment.usedTimes ++;
  17700. //
  17701. data.pipeline = pipeline;
  17702. }
  17703. return data.pipeline;
  17704. }
  17705. /**
  17706. * Deletes the pipeline for the given render object.
  17707. *
  17708. * @param {RenderObject} object - The render object.
  17709. * @return {Object?} The deleted dictionary.
  17710. */
  17711. delete( object ) {
  17712. const pipeline = this.get( object ).pipeline;
  17713. if ( pipeline ) {
  17714. // pipeline
  17715. pipeline.usedTimes --;
  17716. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17717. // programs
  17718. if ( pipeline.isComputePipeline ) {
  17719. pipeline.computeProgram.usedTimes --;
  17720. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17721. } else {
  17722. pipeline.fragmentProgram.usedTimes --;
  17723. pipeline.vertexProgram.usedTimes --;
  17724. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17725. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17726. }
  17727. }
  17728. return super.delete( object );
  17729. }
  17730. /**
  17731. * Frees internal resources.
  17732. */
  17733. dispose() {
  17734. super.dispose();
  17735. this.caches = new Map();
  17736. this.programs = {
  17737. vertex: new Map(),
  17738. fragment: new Map(),
  17739. compute: new Map()
  17740. };
  17741. }
  17742. /**
  17743. * Updates the pipeline for the given render object.
  17744. *
  17745. * @param {RenderObject} renderObject - The render object.
  17746. */
  17747. updateForRender( renderObject ) {
  17748. this.getForRender( renderObject );
  17749. }
  17750. /**
  17751. * Returns a compute pipeline for the given parameters.
  17752. *
  17753. * @private
  17754. * @param {Node} computeNode - The compute node.
  17755. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17756. * @param {String} cacheKey - The cache key.
  17757. * @param {Array<BindGroup>} bindings - The bindings.
  17758. * @return {ComputePipeline} The compute pipeline.
  17759. */
  17760. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17761. // check for existing pipeline
  17762. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17763. let pipeline = this.caches.get( cacheKey );
  17764. if ( pipeline === undefined ) {
  17765. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17766. this.caches.set( cacheKey, pipeline );
  17767. this.backend.createComputePipeline( pipeline, bindings );
  17768. }
  17769. return pipeline;
  17770. }
  17771. /**
  17772. * Returns a render pipeline for the given parameters.
  17773. *
  17774. * @private
  17775. * @param {RenderObject} renderObject - The render object.
  17776. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17777. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17778. * @param {String} cacheKey - The cache key.
  17779. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17780. * @return {ComputePipeline} The compute pipeline.
  17781. */
  17782. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17783. // check for existing pipeline
  17784. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17785. let pipeline = this.caches.get( cacheKey );
  17786. if ( pipeline === undefined ) {
  17787. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17788. this.caches.set( cacheKey, pipeline );
  17789. renderObject.pipeline = pipeline;
  17790. // The `promises` array is `null` by default and only set to an empty array when
  17791. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17792. // pending promises that resolve when the render pipelines are ready for rendering.
  17793. this.backend.createRenderPipeline( renderObject, promises );
  17794. }
  17795. return pipeline;
  17796. }
  17797. /**
  17798. * Computes a cache key representing a compute pipeline.
  17799. *
  17800. * @private
  17801. * @param {Node} computeNode - The compute node.
  17802. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17803. * @return {String} The cache key.
  17804. */
  17805. _getComputeCacheKey( computeNode, stageCompute ) {
  17806. return computeNode.id + ',' + stageCompute.id;
  17807. }
  17808. /**
  17809. * Computes a cache key representing a render pipeline.
  17810. *
  17811. * @private
  17812. * @param {RenderObject} renderObject - The render object.
  17813. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17814. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17815. * @return {String} The cache key.
  17816. */
  17817. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17818. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17819. }
  17820. /**
  17821. * Releases the given pipeline.
  17822. *
  17823. * @private
  17824. * @param {Pipeline} pipeline - The pipeline to release.
  17825. */
  17826. _releasePipeline( pipeline ) {
  17827. this.caches.delete( pipeline.cacheKey );
  17828. }
  17829. /**
  17830. * Releases the shader program.
  17831. *
  17832. * @private
  17833. * @param {Object} program - The shader program to release.
  17834. */
  17835. _releaseProgram( program ) {
  17836. const code = program.code;
  17837. const stage = program.stage;
  17838. this.programs[ stage ].delete( code );
  17839. }
  17840. /**
  17841. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17842. *
  17843. * @private
  17844. * @param {Node} computeNode - The compute node.
  17845. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17846. */
  17847. _needsComputeUpdate( computeNode ) {
  17848. const data = this.get( computeNode );
  17849. return data.pipeline === undefined || data.version !== computeNode.version;
  17850. }
  17851. /**
  17852. * Returns `true` if the render pipeline for the given render object requires an update.
  17853. *
  17854. * @private
  17855. * @param {RenderObject} renderObject - The render object.
  17856. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17857. */
  17858. _needsRenderUpdate( renderObject ) {
  17859. const data = this.get( renderObject );
  17860. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17861. }
  17862. }
  17863. /**
  17864. * This renderer module manages the bindings of the renderer.
  17865. *
  17866. * @private
  17867. * @augments DataMap
  17868. */
  17869. class Bindings extends DataMap {
  17870. /**
  17871. * Constructs a new bindings management component.
  17872. *
  17873. * @param {Backend} backend - The renderer's backend.
  17874. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17875. * @param {Textures} textures - Renderer component for managing textures.
  17876. * @param {Attributes} attributes - Renderer component for managing attributes.
  17877. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17878. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17879. */
  17880. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17881. super();
  17882. /**
  17883. * The renderer's backend.
  17884. *
  17885. * @type {Backend}
  17886. */
  17887. this.backend = backend;
  17888. /**
  17889. * Renderer component for managing textures.
  17890. *
  17891. * @type {Textures}
  17892. */
  17893. this.textures = textures;
  17894. /**
  17895. * Renderer component for managing pipelines.
  17896. *
  17897. * @type {Pipelines}
  17898. */
  17899. this.pipelines = pipelines;
  17900. /**
  17901. * Renderer component for managing attributes.
  17902. *
  17903. * @type {Attributes}
  17904. */
  17905. this.attributes = attributes;
  17906. /**
  17907. * Renderer component for managing nodes related logic.
  17908. *
  17909. * @type {Nodes}
  17910. */
  17911. this.nodes = nodes;
  17912. /**
  17913. * Renderer component for managing metrics and monitoring data.
  17914. *
  17915. * @type {Info}
  17916. */
  17917. this.info = info;
  17918. this.pipelines.bindings = this; // assign bindings to pipelines
  17919. }
  17920. /**
  17921. * Returns the bind groups for the given render object.
  17922. *
  17923. * @param {RenderObject} renderObject - The render object.
  17924. * @return {Array<BindGroup>} The bind groups.
  17925. */
  17926. getForRender( renderObject ) {
  17927. const bindings = renderObject.getBindings();
  17928. for ( const bindGroup of bindings ) {
  17929. const groupData = this.get( bindGroup );
  17930. if ( groupData.bindGroup === undefined ) {
  17931. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17932. this._init( bindGroup );
  17933. this.backend.createBindings( bindGroup, bindings, 0 );
  17934. groupData.bindGroup = bindGroup;
  17935. }
  17936. }
  17937. return bindings;
  17938. }
  17939. /**
  17940. * Returns the bind groups for the given compute node.
  17941. *
  17942. * @param {Node} computeNode - The compute node.
  17943. * @return {Array<BindGroup>} The bind groups.
  17944. */
  17945. getForCompute( computeNode ) {
  17946. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17947. for ( const bindGroup of bindings ) {
  17948. const groupData = this.get( bindGroup );
  17949. if ( groupData.bindGroup === undefined ) {
  17950. this._init( bindGroup );
  17951. this.backend.createBindings( bindGroup, bindings, 0 );
  17952. groupData.bindGroup = bindGroup;
  17953. }
  17954. }
  17955. return bindings;
  17956. }
  17957. /**
  17958. * Updates the bindings for the given compute node.
  17959. *
  17960. * @param {Node} computeNode - The compute node.
  17961. */
  17962. updateForCompute( computeNode ) {
  17963. this._updateBindings( this.getForCompute( computeNode ) );
  17964. }
  17965. /**
  17966. * Updates the bindings for the given render object.
  17967. *
  17968. * @param {RenderObject} renderObject - The render object.
  17969. */
  17970. updateForRender( renderObject ) {
  17971. this._updateBindings( this.getForRender( renderObject ) );
  17972. }
  17973. /**
  17974. * Updates the given array of bindings.
  17975. *
  17976. * @param {Array<BindGroup>} bindings - The bind groups.
  17977. */
  17978. _updateBindings( bindings ) {
  17979. for ( const bindGroup of bindings ) {
  17980. this._update( bindGroup, bindings );
  17981. }
  17982. }
  17983. /**
  17984. * Initializes the given bind group.
  17985. *
  17986. * @param {BindGroup} bindGroup - The bind group to initialize.
  17987. */
  17988. _init( bindGroup ) {
  17989. for ( const binding of bindGroup.bindings ) {
  17990. if ( binding.isSampledTexture ) {
  17991. this.textures.updateTexture( binding.texture );
  17992. } else if ( binding.isStorageBuffer ) {
  17993. const attribute = binding.attribute;
  17994. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17995. this.attributes.update( attribute, attributeType );
  17996. }
  17997. }
  17998. }
  17999. /**
  18000. * Updates the given bind group.
  18001. *
  18002. * @param {BindGroup} bindGroup - The bind group to update.
  18003. * @param {Array<BindGroup>} bindings - The bind groups.
  18004. */
  18005. _update( bindGroup, bindings ) {
  18006. const { backend } = this;
  18007. let needsBindingsUpdate = false;
  18008. let cacheBindings = true;
  18009. let cacheIndex = 0;
  18010. let version = 0;
  18011. // iterate over all bindings and check if buffer updates or a new binding group is required
  18012. for ( const binding of bindGroup.bindings ) {
  18013. if ( binding.isNodeUniformsGroup ) {
  18014. const updated = this.nodes.updateGroup( binding );
  18015. // every uniforms group is a uniform buffer. So if no update is required,
  18016. // we move one with the next binding. Otherwise the next if block will update the group.
  18017. if ( updated === false ) continue;
  18018. }
  18019. if ( binding.isUniformBuffer ) {
  18020. const updated = binding.update();
  18021. if ( updated ) {
  18022. backend.updateBinding( binding );
  18023. }
  18024. } else if ( binding.isSampler ) {
  18025. binding.update();
  18026. } else if ( binding.isSampledTexture ) {
  18027. const texturesTextureData = this.textures.get( binding.texture );
  18028. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18029. const updated = binding.update();
  18030. const texture = binding.texture;
  18031. if ( updated ) {
  18032. this.textures.updateTexture( texture );
  18033. }
  18034. const textureData = backend.get( texture );
  18035. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18036. cacheBindings = false;
  18037. } else {
  18038. cacheIndex = cacheIndex * 10 + texture.id;
  18039. version += texture.version;
  18040. }
  18041. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18042. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18043. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18044. this.textures.updateTexture( texture );
  18045. needsBindingsUpdate = true;
  18046. }
  18047. if ( texture.isStorageTexture === true ) {
  18048. const textureData = this.get( texture );
  18049. if ( binding.store === true ) {
  18050. textureData.needsMipmap = true;
  18051. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18052. this.backend.generateMipmaps( texture );
  18053. textureData.needsMipmap = false;
  18054. }
  18055. }
  18056. }
  18057. }
  18058. if ( needsBindingsUpdate === true ) {
  18059. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18060. }
  18061. }
  18062. }
  18063. /**
  18064. * Default sorting function for opaque render items.
  18065. *
  18066. * @private
  18067. * @function
  18068. * @param {Object} a - The first render item.
  18069. * @param {Object} b - The second render item.
  18070. * @return {Number} A numeric value which defines the sort order.
  18071. */
  18072. function painterSortStable( a, b ) {
  18073. if ( a.groupOrder !== b.groupOrder ) {
  18074. return a.groupOrder - b.groupOrder;
  18075. } else if ( a.renderOrder !== b.renderOrder ) {
  18076. return a.renderOrder - b.renderOrder;
  18077. } else if ( a.material.id !== b.material.id ) {
  18078. return a.material.id - b.material.id;
  18079. } else if ( a.z !== b.z ) {
  18080. return a.z - b.z;
  18081. } else {
  18082. return a.id - b.id;
  18083. }
  18084. }
  18085. /**
  18086. * Default sorting function for transparent render items.
  18087. *
  18088. * @private
  18089. * @function
  18090. * @param {Object} a - The first render item.
  18091. * @param {Object} b - The second render item.
  18092. * @return {Number} A numeric value which defines the sort order.
  18093. */
  18094. function reversePainterSortStable( a, b ) {
  18095. if ( a.groupOrder !== b.groupOrder ) {
  18096. return a.groupOrder - b.groupOrder;
  18097. } else if ( a.renderOrder !== b.renderOrder ) {
  18098. return a.renderOrder - b.renderOrder;
  18099. } else if ( a.z !== b.z ) {
  18100. return b.z - a.z;
  18101. } else {
  18102. return a.id - b.id;
  18103. }
  18104. }
  18105. /**
  18106. * Returns `true` if the given transparent material requires a double pass.
  18107. *
  18108. * @private
  18109. * @function
  18110. * @param {Material} material - The transparent material.
  18111. * @return {Boolean} Whether the given material requires a double pass or not.
  18112. */
  18113. function needsDoublePass( material ) {
  18114. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18115. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18116. }
  18117. /**
  18118. * When the renderer analyzes the scene at the beginning of a render call,
  18119. * it stores 3D object for further processing in render lists. Depending on the
  18120. * properties of a 3D objects (like their transformation or material state), the
  18121. * objects are maintained in ordered lists for the actual rendering.
  18122. *
  18123. * Render lists are unique per scene and camera combination.
  18124. *
  18125. * @private
  18126. * @augments Pipeline
  18127. */
  18128. class RenderList {
  18129. /**
  18130. * Constructs a render list.
  18131. *
  18132. * @param {Lighting} lighting - The lighting management component.
  18133. * @param {Scene} scene - The scene.
  18134. * @param {Camera} camera - The camera the scene is rendered with.
  18135. */
  18136. constructor( lighting, scene, camera ) {
  18137. /**
  18138. * 3D objects are transformed into render items and stored in this array.
  18139. *
  18140. * @type {Array<Object>}
  18141. */
  18142. this.renderItems = [];
  18143. /**
  18144. * The current render items index.
  18145. *
  18146. * @type {Number}
  18147. * @default 0
  18148. */
  18149. this.renderItemsIndex = 0;
  18150. /**
  18151. * A list with opaque render items.
  18152. *
  18153. * @type {Array<Object>}
  18154. */
  18155. this.opaque = [];
  18156. /**
  18157. * A list with transparent render items which require
  18158. * double pass rendering (e.g. transmissive objects).
  18159. *
  18160. * @type {Array<Object>}
  18161. */
  18162. this.transparentDoublePass = [];
  18163. /**
  18164. * A list with transparent render items.
  18165. *
  18166. * @type {Array<Object>}
  18167. */
  18168. this.transparent = [];
  18169. /**
  18170. * A list with transparent render bundle data.
  18171. *
  18172. * @type {Array<Object>}
  18173. */
  18174. this.bundles = [];
  18175. /**
  18176. * The render list's lights node. This node is later
  18177. * relevant for the actual analytical light nodes which
  18178. * compute the scene's lighting in the shader.
  18179. *
  18180. * @type {LightsNode}
  18181. */
  18182. this.lightsNode = lighting.getNode( scene, camera );
  18183. /**
  18184. * The scene's lights stored in an array. This array
  18185. * is used to setup the lights node.
  18186. *
  18187. * @type {Array<Light>}
  18188. */
  18189. this.lightsArray = [];
  18190. /**
  18191. * The scene.
  18192. *
  18193. * @type {Scene}
  18194. */
  18195. this.scene = scene;
  18196. /**
  18197. * The camera the scene is rendered with.
  18198. *
  18199. * @type {Camera}
  18200. */
  18201. this.camera = camera;
  18202. /**
  18203. * How many objects perform occlusion query tests.
  18204. *
  18205. * @type {Number}
  18206. * @default 0
  18207. */
  18208. this.occlusionQueryCount = 0;
  18209. }
  18210. /**
  18211. * This method is called right at the beginning of a render call
  18212. * before the scene is analyzed. It prepares the internal data
  18213. * structures for the upcoming render lists generation.
  18214. *
  18215. * @return {RenderList} A reference to this render list.
  18216. */
  18217. begin() {
  18218. this.renderItemsIndex = 0;
  18219. this.opaque.length = 0;
  18220. this.transparentDoublePass.length = 0;
  18221. this.transparent.length = 0;
  18222. this.bundles.length = 0;
  18223. this.lightsArray.length = 0;
  18224. this.occlusionQueryCount = 0;
  18225. return this;
  18226. }
  18227. /**
  18228. * Returns a render item for the giving render item state. The state is defined
  18229. * by a series of object-related parameters.
  18230. *
  18231. * The method avoids object creation by holding render items and reusing them in
  18232. * subsequent render calls (just with different property values).
  18233. *
  18234. * @param {Object3D} object - The 3D object.
  18235. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18236. * @param {Material} material - The 3D object's material.
  18237. * @param {Number} groupOrder - The current group order.
  18238. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18239. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18240. * @param {ClippingContext} clippingContext - The current clipping context.
  18241. * @return {Object} The render item.
  18242. */
  18243. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18244. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18245. if ( renderItem === undefined ) {
  18246. renderItem = {
  18247. id: object.id,
  18248. object: object,
  18249. geometry: geometry,
  18250. material: material,
  18251. groupOrder: groupOrder,
  18252. renderOrder: object.renderOrder,
  18253. z: z,
  18254. group: group,
  18255. clippingContext: clippingContext
  18256. };
  18257. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18258. } else {
  18259. renderItem.id = object.id;
  18260. renderItem.object = object;
  18261. renderItem.geometry = geometry;
  18262. renderItem.material = material;
  18263. renderItem.groupOrder = groupOrder;
  18264. renderItem.renderOrder = object.renderOrder;
  18265. renderItem.z = z;
  18266. renderItem.group = group;
  18267. renderItem.clippingContext = clippingContext;
  18268. }
  18269. this.renderItemsIndex ++;
  18270. return renderItem;
  18271. }
  18272. /**
  18273. * Pushes the given object as a render item to the internal render lists.
  18274. * The selected lists depend on the object properties.
  18275. *
  18276. * @param {Object3D} object - The 3D object.
  18277. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18278. * @param {Material} material - The 3D object's material.
  18279. * @param {Number} groupOrder - The current group order.
  18280. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18281. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18282. * @param {ClippingContext} clippingContext - The current clipping context.
  18283. */
  18284. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18285. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18286. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18287. if ( material.transparent === true || material.transmission > 0 ) {
  18288. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18289. this.transparent.push( renderItem );
  18290. } else {
  18291. this.opaque.push( renderItem );
  18292. }
  18293. }
  18294. /**
  18295. * Inserts the given object as a render item at the start of the internal render lists.
  18296. * The selected lists depend on the object properties.
  18297. *
  18298. * @param {Object3D} object - The 3D object.
  18299. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18300. * @param {Material} material - The 3D object's material.
  18301. * @param {Number} groupOrder - The current group order.
  18302. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18303. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18304. * @param {ClippingContext} clippingContext - The current clipping context.
  18305. */
  18306. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18307. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18308. if ( material.transparent === true || material.transmission > 0 ) {
  18309. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18310. this.transparent.unshift( renderItem );
  18311. } else {
  18312. this.opaque.unshift( renderItem );
  18313. }
  18314. }
  18315. /**
  18316. * Pushes render bundle group data into the render list.
  18317. *
  18318. * @param {Object} group - Bundle group data.
  18319. */
  18320. pushBundle( group ) {
  18321. this.bundles.push( group );
  18322. }
  18323. /**
  18324. * Pushes a light into the render list.
  18325. *
  18326. * @param {Light} light - The light.
  18327. */
  18328. pushLight( light ) {
  18329. this.lightsArray.push( light );
  18330. }
  18331. /**
  18332. * Sorts the internal render lists.
  18333. *
  18334. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18335. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18336. */
  18337. sort( customOpaqueSort, customTransparentSort ) {
  18338. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18339. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18340. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18341. }
  18342. /**
  18343. * This method performs finalizing tasks right after the render lists
  18344. * have been generated.
  18345. */
  18346. finish() {
  18347. // update lights
  18348. this.lightsNode.setLights( this.lightsArray );
  18349. // Clear references from inactive renderItems in the list
  18350. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18351. const renderItem = this.renderItems[ i ];
  18352. if ( renderItem.id === null ) break;
  18353. renderItem.id = null;
  18354. renderItem.object = null;
  18355. renderItem.geometry = null;
  18356. renderItem.material = null;
  18357. renderItem.groupOrder = null;
  18358. renderItem.renderOrder = null;
  18359. renderItem.z = null;
  18360. renderItem.group = null;
  18361. renderItem.clippingContext = null;
  18362. }
  18363. }
  18364. }
  18365. const _chainKeys$4 = [];
  18366. /**
  18367. * This renderer module manages the render lists which are unique
  18368. * per scene and camera combination.
  18369. *
  18370. * @private
  18371. */
  18372. class RenderLists {
  18373. /**
  18374. * Constructs a render lists management component.
  18375. *
  18376. * @param {Lighting} lighting - The lighting management component.
  18377. */
  18378. constructor( lighting ) {
  18379. /**
  18380. * The lighting management component.
  18381. *
  18382. * @type {Lighting}
  18383. */
  18384. this.lighting = lighting;
  18385. /**
  18386. * The internal chain map which holds the render lists.
  18387. *
  18388. * @type {ChainMap}
  18389. */
  18390. this.lists = new ChainMap();
  18391. }
  18392. /**
  18393. * Returns a render list for the given scene and camera.
  18394. *
  18395. * @param {Scene} scene - The scene.
  18396. * @param {Camera} camera - The camera.
  18397. * @return {RenderList} The render list.
  18398. */
  18399. get( scene, camera ) {
  18400. const lists = this.lists;
  18401. _chainKeys$4[ 0 ] = scene;
  18402. _chainKeys$4[ 1 ] = camera;
  18403. let list = lists.get( _chainKeys$4 );
  18404. if ( list === undefined ) {
  18405. list = new RenderList( this.lighting, scene, camera );
  18406. lists.set( _chainKeys$4, list );
  18407. }
  18408. _chainKeys$4.length = 0;
  18409. return list;
  18410. }
  18411. /**
  18412. * Frees all internal resources.
  18413. */
  18414. dispose() {
  18415. this.lists = new ChainMap();
  18416. }
  18417. }
  18418. let _id$7 = 0;
  18419. /**
  18420. * Any render or compute command is executed in a specific context that defines
  18421. * the state of the renderer and its backend. Typical examples for such context
  18422. * data are the current clear values or data from the active framebuffer. This
  18423. * module is used to represent these contexts as objects.
  18424. *
  18425. * @private
  18426. */
  18427. class RenderContext {
  18428. /**
  18429. * Constructs a new render context.
  18430. */
  18431. constructor() {
  18432. /**
  18433. * The context's ID.
  18434. *
  18435. * @type {Number}
  18436. */
  18437. this.id = _id$7 ++;
  18438. /**
  18439. * Whether the current active framebuffer has a color attachment.
  18440. *
  18441. * @type {Boolean}
  18442. * @default true
  18443. */
  18444. this.color = true;
  18445. /**
  18446. * Whether the color attachment should be cleared or not.
  18447. *
  18448. * @type {Boolean}
  18449. * @default true
  18450. */
  18451. this.clearColor = true;
  18452. /**
  18453. * The clear color value.
  18454. *
  18455. * @type {Object}
  18456. * @default true
  18457. */
  18458. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18459. /**
  18460. * Whether the current active framebuffer has a depth attachment.
  18461. *
  18462. * @type {Boolean}
  18463. * @default true
  18464. */
  18465. this.depth = true;
  18466. /**
  18467. * Whether the depth attachment should be cleared or not.
  18468. *
  18469. * @type {Boolean}
  18470. * @default true
  18471. */
  18472. this.clearDepth = true;
  18473. /**
  18474. * The clear depth value.
  18475. *
  18476. * @type {Number}
  18477. * @default 1
  18478. */
  18479. this.clearDepthValue = 1;
  18480. /**
  18481. * Whether the current active framebuffer has a stencil attachment.
  18482. *
  18483. * @type {Boolean}
  18484. * @default false
  18485. */
  18486. this.stencil = false;
  18487. /**
  18488. * Whether the stencil attachment should be cleared or not.
  18489. *
  18490. * @type {Boolean}
  18491. * @default true
  18492. */
  18493. this.clearStencil = true;
  18494. /**
  18495. * The clear stencil value.
  18496. *
  18497. * @type {Number}
  18498. * @default 1
  18499. */
  18500. this.clearStencilValue = 1;
  18501. /**
  18502. * By default the viewport encloses the entire framebuffer If a smaller
  18503. * viewport is manually defined, this property is to `true` by the renderer.
  18504. *
  18505. * @type {Boolean}
  18506. * @default false
  18507. */
  18508. this.viewport = false;
  18509. /**
  18510. * The viewport value. This value is in physical pixels meaning it incorporates
  18511. * the renderer's pixel ratio. The viewport property of render targets or
  18512. * the renderer is in logical pixels.
  18513. *
  18514. * @type {Vector4}
  18515. */
  18516. this.viewportValue = new Vector4();
  18517. /**
  18518. * When the scissor test is active and scissor rectangle smaller than the
  18519. * framebuffers dimensions, this property is to `true` by the renderer.
  18520. *
  18521. * @type {Boolean}
  18522. * @default false
  18523. */
  18524. this.scissor = false;
  18525. /**
  18526. * The scissor rectangle.
  18527. *
  18528. * @type {Vector4}
  18529. */
  18530. this.scissorValue = new Vector4();
  18531. /**
  18532. * The active render target.
  18533. *
  18534. * @type {RenderTarget?}
  18535. * @default null
  18536. */
  18537. this.renderTarget = null;
  18538. /**
  18539. * The textures of the active render target.
  18540. * `null` when no render target is set.
  18541. *
  18542. * @type {Array<Texture>?}
  18543. * @default null
  18544. */
  18545. this.textures = null;
  18546. /**
  18547. * The depth texture of the active render target.
  18548. * `null` when no render target is set.
  18549. *
  18550. * @type {DepthTexture?}
  18551. * @default null
  18552. */
  18553. this.depthTexture = null;
  18554. /**
  18555. * The active cube face.
  18556. *
  18557. * @type {Number}
  18558. * @default 0
  18559. */
  18560. this.activeCubeFace = 0;
  18561. /**
  18562. * The active mipmap level.
  18563. *
  18564. * @type {Number}
  18565. * @default 0
  18566. */
  18567. this.activeMipmapLevel = 0;
  18568. /**
  18569. * The number of MSAA samples. This value is always `1` when
  18570. * MSAA isn't used.
  18571. *
  18572. * @type {Number}
  18573. * @default 1
  18574. */
  18575. this.sampleCount = 1;
  18576. /**
  18577. * The active render target's width in physical pixels.
  18578. *
  18579. * @type {Number}
  18580. * @default 0
  18581. */
  18582. this.width = 0;
  18583. /**
  18584. * The active render target's height in physical pixels.
  18585. *
  18586. * @type {Number}
  18587. * @default 0
  18588. */
  18589. this.height = 0;
  18590. /**
  18591. * The occlusion query count.
  18592. *
  18593. * @type {Number}
  18594. * @default 0
  18595. */
  18596. this.occlusionQueryCount = 0;
  18597. /**
  18598. * The current clipping context.
  18599. *
  18600. * @type {ClippingContext?}
  18601. * @default null
  18602. */
  18603. this.clippingContext = null;
  18604. /**
  18605. * This flag can be used for type testing.
  18606. *
  18607. * @type {Boolean}
  18608. * @readonly
  18609. * @default true
  18610. */
  18611. this.isRenderContext = true;
  18612. }
  18613. /**
  18614. * Returns the cache key of this render context.
  18615. *
  18616. * @return {Number} The cache key.
  18617. */
  18618. getCacheKey() {
  18619. return getCacheKey( this );
  18620. }
  18621. }
  18622. /**
  18623. * Computes a cache key for the given render context. This key
  18624. * should identify the render target state so it is possible to
  18625. * configure the correct attachments in the respective backend.
  18626. *
  18627. * @param {RenderContext} renderContext - The render context.
  18628. * @return {Number} The cache key.
  18629. */
  18630. function getCacheKey( renderContext ) {
  18631. const { textures, activeCubeFace } = renderContext;
  18632. const values = [ activeCubeFace ];
  18633. for ( const texture of textures ) {
  18634. values.push( texture.id );
  18635. }
  18636. return hashArray( values );
  18637. }
  18638. const _chainKeys$3 = [];
  18639. const _defaultScene = /*@__PURE__*/ new Scene();
  18640. const _defaultCamera = /*@__PURE__*/ new Camera();
  18641. /**
  18642. * This module manages the render contexts of the renderer.
  18643. *
  18644. * @private
  18645. */
  18646. class RenderContexts {
  18647. /**
  18648. * Constructs a new render context management component.
  18649. */
  18650. constructor() {
  18651. /**
  18652. * A dictionary that manages render contexts in chain maps
  18653. * for each attachment state.
  18654. *
  18655. * @type {Object<String,ChainMap>}
  18656. */
  18657. this.chainMaps = {};
  18658. }
  18659. /**
  18660. * Returns a render context for the given scene, camera and render target.
  18661. *
  18662. * @param {Scene} scene - The scene.
  18663. * @param {Camera} camera - The camera that is used to render the scene.
  18664. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18665. * @return {RenderContext} The render context.
  18666. */
  18667. get( scene, camera, renderTarget = null ) {
  18668. _chainKeys$3[ 0 ] = scene;
  18669. _chainKeys$3[ 1 ] = camera;
  18670. let attachmentState;
  18671. if ( renderTarget === null ) {
  18672. attachmentState = 'default';
  18673. } else {
  18674. const format = renderTarget.texture.format;
  18675. const count = renderTarget.textures.length;
  18676. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18677. }
  18678. const chainMap = this._getChainMap( attachmentState );
  18679. let renderState = chainMap.get( _chainKeys$3 );
  18680. if ( renderState === undefined ) {
  18681. renderState = new RenderContext();
  18682. chainMap.set( _chainKeys$3, renderState );
  18683. }
  18684. _chainKeys$3.length = 0;
  18685. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18686. return renderState;
  18687. }
  18688. /**
  18689. * Returns a render context intended for clear operations.
  18690. *
  18691. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18692. * @return {RenderContext} The render context.
  18693. */
  18694. getForClear( renderTarget = null ) {
  18695. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18696. }
  18697. /**
  18698. * Returns a chain map for the given attachment state.
  18699. *
  18700. * @private
  18701. * @param {String} attachmentState - The attachment state.
  18702. * @return {ChainMap} The chain map.
  18703. */
  18704. _getChainMap( attachmentState ) {
  18705. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18706. }
  18707. /**
  18708. * Frees internal resources.
  18709. */
  18710. dispose() {
  18711. this.chainMaps = {};
  18712. }
  18713. }
  18714. const _size$3 = /*@__PURE__*/ new Vector3();
  18715. /**
  18716. * This module manages the textures of the renderer.
  18717. *
  18718. * @private
  18719. * @augments DataMap
  18720. */
  18721. class Textures extends DataMap {
  18722. /**
  18723. * Constructs a new texture management component.
  18724. *
  18725. * @param {Renderer} renderer - The renderer.
  18726. * @param {Backend} backend - The renderer's backend.
  18727. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18728. */
  18729. constructor( renderer, backend, info ) {
  18730. super();
  18731. /**
  18732. * The renderer.
  18733. *
  18734. * @type {Renderer}
  18735. */
  18736. this.renderer = renderer;
  18737. /**
  18738. * The backend.
  18739. *
  18740. * @type {Backend}
  18741. */
  18742. this.backend = backend;
  18743. /**
  18744. * Renderer component for managing metrics and monitoring data.
  18745. *
  18746. * @type {Info}
  18747. */
  18748. this.info = info;
  18749. }
  18750. /**
  18751. * Updates the given render target. Based on the given render target configuration,
  18752. * it updates the texture states representing the attachments of the framebuffer.
  18753. *
  18754. * @param {RenderTarget} renderTarget - The render target to update.
  18755. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18756. */
  18757. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18758. const renderTargetData = this.get( renderTarget );
  18759. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18760. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18761. const textures = renderTarget.textures;
  18762. const size = this.getSize( textures[ 0 ] );
  18763. const mipWidth = size.width >> activeMipmapLevel;
  18764. const mipHeight = size.height >> activeMipmapLevel;
  18765. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18766. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18767. let textureNeedsUpdate = false;
  18768. if ( depthTexture === undefined && useDepthTexture ) {
  18769. depthTexture = new DepthTexture();
  18770. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18771. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18772. depthTexture.image.width = mipWidth;
  18773. depthTexture.image.height = mipHeight;
  18774. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18775. }
  18776. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18777. textureNeedsUpdate = true;
  18778. if ( depthTexture ) {
  18779. depthTexture.needsUpdate = true;
  18780. depthTexture.image.width = mipWidth;
  18781. depthTexture.image.height = mipHeight;
  18782. }
  18783. }
  18784. renderTargetData.width = size.width;
  18785. renderTargetData.height = size.height;
  18786. renderTargetData.textures = textures;
  18787. renderTargetData.depthTexture = depthTexture || null;
  18788. renderTargetData.depth = renderTarget.depthBuffer;
  18789. renderTargetData.stencil = renderTarget.stencilBuffer;
  18790. renderTargetData.renderTarget = renderTarget;
  18791. if ( renderTargetData.sampleCount !== sampleCount ) {
  18792. textureNeedsUpdate = true;
  18793. if ( depthTexture ) {
  18794. depthTexture.needsUpdate = true;
  18795. }
  18796. renderTargetData.sampleCount = sampleCount;
  18797. }
  18798. //
  18799. const options = { sampleCount };
  18800. if ( ( renderTarget.isXRRenderTarget === true && renderTarget.hasExternalTextures === true ) === false ) {
  18801. for ( let i = 0; i < textures.length; i ++ ) {
  18802. const texture = textures[ i ];
  18803. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18804. this.updateTexture( texture, options );
  18805. }
  18806. }
  18807. if ( depthTexture && renderTarget.autoAllocateDepthBuffer !== false ) {
  18808. this.updateTexture( depthTexture, options );
  18809. }
  18810. // dispose handler
  18811. if ( renderTargetData.initialized !== true ) {
  18812. renderTargetData.initialized = true;
  18813. // dispose
  18814. const onDispose = () => {
  18815. renderTarget.removeEventListener( 'dispose', onDispose );
  18816. for ( let i = 0; i < textures.length; i ++ ) {
  18817. this._destroyTexture( textures[ i ] );
  18818. }
  18819. if ( depthTexture ) {
  18820. this._destroyTexture( depthTexture );
  18821. }
  18822. this.delete( renderTarget );
  18823. };
  18824. renderTarget.addEventListener( 'dispose', onDispose );
  18825. }
  18826. }
  18827. /**
  18828. * Updates the given texture. Depending on the texture state, this method
  18829. * triggers the upload of texture data to the GPU memory. If the texture data are
  18830. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18831. *
  18832. * @param {Texture} texture - The texture to update.
  18833. * @param {Object} [options={}] - The options.
  18834. */
  18835. updateTexture( texture, options = {} ) {
  18836. const textureData = this.get( texture );
  18837. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18838. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18839. const backend = this.backend;
  18840. if ( isRenderTarget && textureData.initialized === true ) {
  18841. // it's an update
  18842. backend.destroySampler( texture );
  18843. backend.destroyTexture( texture );
  18844. }
  18845. //
  18846. if ( texture.isFramebufferTexture ) {
  18847. const renderTarget = this.renderer.getRenderTarget();
  18848. if ( renderTarget ) {
  18849. texture.type = renderTarget.texture.type;
  18850. } else {
  18851. texture.type = UnsignedByteType;
  18852. }
  18853. }
  18854. //
  18855. const { width, height, depth } = this.getSize( texture );
  18856. options.width = width;
  18857. options.height = height;
  18858. options.depth = depth;
  18859. options.needsMipmaps = this.needsMipmaps( texture );
  18860. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18861. //
  18862. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18863. backend.createSampler( texture );
  18864. backend.createTexture( texture, options );
  18865. textureData.generation = texture.version;
  18866. } else {
  18867. const needsCreate = textureData.initialized !== true;
  18868. if ( needsCreate ) backend.createSampler( texture );
  18869. if ( texture.version > 0 ) {
  18870. const image = texture.image;
  18871. if ( image === undefined ) {
  18872. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18873. } else if ( image.complete === false ) {
  18874. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18875. } else {
  18876. if ( texture.images ) {
  18877. const images = [];
  18878. for ( const image of texture.images ) {
  18879. images.push( image );
  18880. }
  18881. options.images = images;
  18882. } else {
  18883. options.image = image;
  18884. }
  18885. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18886. backend.createTexture( texture, options );
  18887. textureData.isDefaultTexture = false;
  18888. textureData.generation = texture.version;
  18889. }
  18890. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18891. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18892. }
  18893. } else {
  18894. // async update
  18895. backend.createDefaultTexture( texture );
  18896. textureData.isDefaultTexture = true;
  18897. textureData.generation = texture.version;
  18898. }
  18899. }
  18900. // dispose handler
  18901. if ( textureData.initialized !== true ) {
  18902. textureData.initialized = true;
  18903. textureData.generation = texture.version;
  18904. //
  18905. this.info.memory.textures ++;
  18906. // dispose
  18907. const onDispose = () => {
  18908. texture.removeEventListener( 'dispose', onDispose );
  18909. this._destroyTexture( texture );
  18910. this.info.memory.textures --;
  18911. };
  18912. texture.addEventListener( 'dispose', onDispose );
  18913. }
  18914. //
  18915. textureData.version = texture.version;
  18916. }
  18917. /**
  18918. * Computes the size of the given texture and writes the result
  18919. * into the target vector. This vector is also returned by the
  18920. * method.
  18921. *
  18922. * If no texture data are available for the compute yet, the method
  18923. * returns default size values.
  18924. *
  18925. * @param {Texture} texture - The texture to compute the size for.
  18926. * @param {Vector3} target - The target vector.
  18927. * @return {Vector3} The target vector.
  18928. */
  18929. getSize( texture, target = _size$3 ) {
  18930. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18931. if ( image ) {
  18932. if ( image.image !== undefined ) image = image.image;
  18933. target.width = image.width || 1;
  18934. target.height = image.height || 1;
  18935. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18936. } else {
  18937. target.width = target.height = target.depth = 1;
  18938. }
  18939. return target;
  18940. }
  18941. /**
  18942. * Computes the number of mipmap levels for the given texture.
  18943. *
  18944. * @param {Texture} texture - The texture.
  18945. * @param {Number} width - The texture's width.
  18946. * @param {Number} height - The texture's height.
  18947. * @return {Number} The number of mipmap levels.
  18948. */
  18949. getMipLevels( texture, width, height ) {
  18950. let mipLevelCount;
  18951. if ( texture.isCompressedTexture ) {
  18952. if ( texture.mipmaps ) {
  18953. mipLevelCount = texture.mipmaps.length;
  18954. } else {
  18955. mipLevelCount = 1;
  18956. }
  18957. } else {
  18958. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18959. }
  18960. return mipLevelCount;
  18961. }
  18962. /**
  18963. * Returns `true` if the given texture requires mipmaps.
  18964. *
  18965. * @param {Texture} texture - The texture.
  18966. * @return {Boolean} Whether mipmaps are required or not.
  18967. */
  18968. needsMipmaps( texture ) {
  18969. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18970. }
  18971. /**
  18972. * Returns `true` if the given texture is an environment map.
  18973. *
  18974. * @param {Texture} texture - The texture.
  18975. * @return {Boolean} Whether the given texture is an environment map or not.
  18976. */
  18977. isEnvironmentTexture( texture ) {
  18978. const mapping = texture.mapping;
  18979. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18980. }
  18981. /**
  18982. * Frees internal resource when the given texture isn't
  18983. * required anymore.
  18984. *
  18985. * @param {Texture} texture - The texture to destroy.
  18986. */
  18987. _destroyTexture( texture ) {
  18988. this.backend.destroySampler( texture );
  18989. this.backend.destroyTexture( texture );
  18990. this.delete( texture );
  18991. }
  18992. }
  18993. /**
  18994. * A four-component version of {@link Color} which is internally
  18995. * used by the renderer to represents clear color with alpha as
  18996. * one object.
  18997. *
  18998. * @private
  18999. * @augments Color
  19000. */
  19001. class Color4 extends Color {
  19002. /**
  19003. * Constructs a new four-component color.
  19004. * You can also pass a single THREE.Color, hex or
  19005. * string argument to this constructor.
  19006. *
  19007. * @param {Number|String} [r=1] - The red value.
  19008. * @param {Number} [g=1] - The green value.
  19009. * @param {Number} [b=1] - The blue value.
  19010. * @param {Number} [a=1] - The alpha value.
  19011. */
  19012. constructor( r, g, b, a = 1 ) {
  19013. super( r, g, b );
  19014. this.a = a;
  19015. }
  19016. /**
  19017. * Overwrites the default to honor alpha.
  19018. * You can also pass a single THREE.Color, hex or
  19019. * string argument to this method.
  19020. *
  19021. * @param {Number|String} r - The red value.
  19022. * @param {Number} g - The green value.
  19023. * @param {Number} b - The blue value.
  19024. * @param {Number} [a=1] - The alpha value.
  19025. * @return {Color4} A reference to this object.
  19026. */
  19027. set( r, g, b, a = 1 ) {
  19028. this.a = a;
  19029. return super.set( r, g, b );
  19030. }
  19031. /**
  19032. * Overwrites the default to honor alpha.
  19033. *
  19034. * @param {Color4} color - The color to copy.
  19035. * @return {Color4} A reference to this object.
  19036. */
  19037. copy( color ) {
  19038. if ( color.a !== undefined ) this.a = color.a;
  19039. return super.copy( color );
  19040. }
  19041. /**
  19042. * Overwrites the default to honor alpha.
  19043. *
  19044. * @return {Color4} The cloned color.
  19045. */
  19046. clone() {
  19047. return new this.constructor( this.r, this.g, this.b, this.a );
  19048. }
  19049. }
  19050. /** @module ParameterNode **/
  19051. /**
  19052. * Special version of {@link PropertyNode} which is used for parameters.
  19053. *
  19054. * @augments PropertyNode
  19055. */
  19056. class ParameterNode extends PropertyNode {
  19057. static get type() {
  19058. return 'ParameterNode';
  19059. }
  19060. /**
  19061. * Constructs a new parameter node.
  19062. *
  19063. * @param {String} nodeType - The type of the node.
  19064. * @param {String?} [name=null] - The name of the parameter in the shader.
  19065. */
  19066. constructor( nodeType, name = null ) {
  19067. super( nodeType, name );
  19068. /**
  19069. * This flag can be used for type testing.
  19070. *
  19071. * @type {Boolean}
  19072. * @readonly
  19073. * @default true
  19074. */
  19075. this.isParameterNode = true;
  19076. }
  19077. getHash() {
  19078. return this.uuid;
  19079. }
  19080. generate() {
  19081. return this.name;
  19082. }
  19083. }
  19084. /**
  19085. * TSL function for creating a parameter node.
  19086. *
  19087. * @function
  19088. * @param {String} type - The type of the node.
  19089. * @param {String?} name - The name of the parameter in the shader.
  19090. * @returns {ParameterNode}
  19091. */
  19092. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19093. /** @module StackNode **/
  19094. /**
  19095. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19096. * They are usually needed in cases like `If`, `Else`.
  19097. *
  19098. * @augments Node
  19099. */
  19100. class StackNode extends Node {
  19101. static get type() {
  19102. return 'StackNode';
  19103. }
  19104. /**
  19105. * Constructs a new stack node.
  19106. *
  19107. * @param {StackNode?} [parent=null] - The parent stack node.
  19108. */
  19109. constructor( parent = null ) {
  19110. super();
  19111. /**
  19112. * List of nodes.
  19113. *
  19114. * @type {Array<Node>}
  19115. */
  19116. this.nodes = [];
  19117. /**
  19118. * The output node.
  19119. *
  19120. * @type {Node?}
  19121. * @default null
  19122. */
  19123. this.outputNode = null;
  19124. /**
  19125. * The parent stack node.
  19126. *
  19127. * @type {StackNode}
  19128. * @default null
  19129. */
  19130. this.parent = parent;
  19131. /**
  19132. * The current conditional node.
  19133. *
  19134. * @private
  19135. * @type {ConditionalNode}
  19136. * @default null
  19137. */
  19138. this._currentCond = null;
  19139. /**
  19140. * This flag can be used for type testing.
  19141. *
  19142. * @type {Boolean}
  19143. * @readonly
  19144. * @default true
  19145. */
  19146. this.isStackNode = true;
  19147. }
  19148. getNodeType( builder ) {
  19149. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19150. }
  19151. /**
  19152. * Adds a node to this stack.
  19153. *
  19154. * @param {Node} node - The node to add.
  19155. * @return {StackNode} A reference to this stack node.
  19156. */
  19157. add( node ) {
  19158. this.nodes.push( node );
  19159. return this;
  19160. }
  19161. /**
  19162. * Represent an `if` statement in TSL.
  19163. *
  19164. * @param {Node} boolNode - Represents the condition.
  19165. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19166. * @return {StackNode} A reference to this stack node.
  19167. */
  19168. If( boolNode, method ) {
  19169. const methodNode = new ShaderNode( method );
  19170. this._currentCond = select( boolNode, methodNode );
  19171. return this.add( this._currentCond );
  19172. }
  19173. /**
  19174. * Represent an `elseif` statement in TSL.
  19175. *
  19176. * @param {Node} boolNode - Represents the condition.
  19177. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19178. * @return {StackNode} A reference to this stack node.
  19179. */
  19180. ElseIf( boolNode, method ) {
  19181. const methodNode = new ShaderNode( method );
  19182. const ifNode = select( boolNode, methodNode );
  19183. this._currentCond.elseNode = ifNode;
  19184. this._currentCond = ifNode;
  19185. return this;
  19186. }
  19187. /**
  19188. * Represent an `else` statement in TSL.
  19189. *
  19190. * @param {Function} method - TSL code which is executed in the `else` case.
  19191. * @return {StackNode} A reference to this stack node.
  19192. */
  19193. Else( method ) {
  19194. this._currentCond.elseNode = new ShaderNode( method );
  19195. return this;
  19196. }
  19197. build( builder, ...params ) {
  19198. const previousStack = getCurrentStack();
  19199. setCurrentStack( this );
  19200. for ( const node of this.nodes ) {
  19201. node.build( builder, 'void' );
  19202. }
  19203. setCurrentStack( previousStack );
  19204. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19205. }
  19206. // Deprecated
  19207. /**
  19208. * @function
  19209. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19210. *
  19211. * @param {...any} params
  19212. * @returns {StackNode}
  19213. */
  19214. else( ...params ) { // @deprecated, r168
  19215. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19216. return this.Else( ...params );
  19217. }
  19218. /**
  19219. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19220. *
  19221. * @param {...any} params
  19222. * @returns {StackNode}
  19223. */
  19224. elseif( ...params ) { // @deprecated, r168
  19225. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19226. return this.ElseIf( ...params );
  19227. }
  19228. }
  19229. /**
  19230. * TSL function for creating a stack node.
  19231. *
  19232. * @function
  19233. * @param {StackNode?} [parent=null] - The parent stack node.
  19234. * @returns {StackNode}
  19235. */
  19236. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19237. /** @module OutputStructNode **/
  19238. /**
  19239. * This node can be used to define multiple outputs in a shader programs.
  19240. *
  19241. * @augments Node
  19242. */
  19243. class OutputStructNode extends Node {
  19244. static get type() {
  19245. return 'OutputStructNode';
  19246. }
  19247. /**
  19248. * Constructs a new output struct node. The constructor can be invoked with an
  19249. * arbitrary number of nodes representing the members.
  19250. *
  19251. * @param {...Node} members - A parameter list of nodes.
  19252. */
  19253. constructor( ...members ) {
  19254. super();
  19255. /**
  19256. * An array of nodes which defines the output.
  19257. *
  19258. * @type {Array<Node>}
  19259. */
  19260. this.members = members;
  19261. /**
  19262. * This flag can be used for type testing.
  19263. *
  19264. * @type {Boolean}
  19265. * @readonly
  19266. * @default true
  19267. */
  19268. this.isOutputStructNode = true;
  19269. }
  19270. setup( builder ) {
  19271. super.setup( builder );
  19272. const members = this.members;
  19273. const types = [];
  19274. for ( let i = 0; i < members.length; i ++ ) {
  19275. types.push( members[ i ].getNodeType( builder ) );
  19276. }
  19277. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19278. }
  19279. generate( builder, output ) {
  19280. const propertyName = builder.getOutputStructName();
  19281. const members = this.members;
  19282. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19283. for ( let i = 0; i < members.length; i ++ ) {
  19284. const snippet = members[ i ].build( builder, output );
  19285. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19286. }
  19287. return propertyName;
  19288. }
  19289. }
  19290. /**
  19291. * TSL function for creating an output struct node.
  19292. *
  19293. * @function
  19294. * @param {...Node} members - A parameter list of nodes.
  19295. * @returns {OutputStructNode}
  19296. */
  19297. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19298. /** @module MRTNode **/
  19299. /**
  19300. * Returns the MRT texture index for the given name.
  19301. *
  19302. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19303. * @param {String} name - The name of the MRT texture which index is requested.
  19304. * @return {Number} The texture index.
  19305. */
  19306. function getTextureIndex( textures, name ) {
  19307. for ( let i = 0; i < textures.length; i ++ ) {
  19308. if ( textures[ i ].name === name ) {
  19309. return i;
  19310. }
  19311. }
  19312. return -1;
  19313. }
  19314. /**
  19315. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19316. * post-processing is shown below:
  19317. * ```js
  19318. * const mrtNode = mrt( {
  19319. * output: output,
  19320. * normal: normalView
  19321. * } ) );
  19322. * ```
  19323. * The MRT output is defined as a dictionary.
  19324. *
  19325. * @augments OutputStructNode
  19326. */
  19327. class MRTNode extends OutputStructNode {
  19328. static get type() {
  19329. return 'MRTNode';
  19330. }
  19331. /**
  19332. * Constructs a new output struct node.
  19333. *
  19334. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19335. */
  19336. constructor( outputNodes ) {
  19337. super();
  19338. /**
  19339. * A dictionary representing the MRT outputs. The key
  19340. * is the name of the output, the value the node which produces
  19341. * the output result.
  19342. *
  19343. * @type {Object<String, Node>}
  19344. */
  19345. this.outputNodes = outputNodes;
  19346. /**
  19347. * This flag can be used for type testing.
  19348. *
  19349. * @type {Boolean}
  19350. * @readonly
  19351. * @default true
  19352. */
  19353. this.isMRTNode = true;
  19354. }
  19355. /**
  19356. * Returns `true` if the MRT node has an output with the given name.
  19357. *
  19358. * @param {String} name - The name of the output.
  19359. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19360. */
  19361. has( name ) {
  19362. return this.outputNodes[ name ] !== undefined;
  19363. }
  19364. /**
  19365. * Returns the output node for the given name.
  19366. *
  19367. * @param {String} name - The name of the output.
  19368. * @return {Node} The output node.
  19369. */
  19370. get( name ) {
  19371. return this.outputNodes[ name ];
  19372. }
  19373. /**
  19374. * Merges the outputs of the given MRT node with the outputs of this node.
  19375. *
  19376. * @param {MRTNode} mrtNode - The MRT to merge.
  19377. * @return {MRTNode} A new MRT node with merged outputs..
  19378. */
  19379. merge( mrtNode ) {
  19380. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19381. return mrt( outputs );
  19382. }
  19383. setup( builder ) {
  19384. const outputNodes = this.outputNodes;
  19385. const mrt = builder.renderer.getRenderTarget();
  19386. const members = [];
  19387. const textures = mrt.textures;
  19388. for ( const name in outputNodes ) {
  19389. const index = getTextureIndex( textures, name );
  19390. members[ index ] = vec4( outputNodes[ name ] );
  19391. }
  19392. this.members = members;
  19393. return super.setup( builder );
  19394. }
  19395. }
  19396. /**
  19397. * TSL function for creating a MRT node.
  19398. *
  19399. * @function
  19400. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19401. * @returns {MRTNode}
  19402. */
  19403. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19404. /** @module Hash **/
  19405. /**
  19406. * Generates a hash value in the range `[0, 1]` from the given seed.
  19407. *
  19408. * @method
  19409. * @param {Node<float>} seed - The seed.
  19410. * @return {Node<float>} The hash value.
  19411. */
  19412. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19413. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19414. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19415. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19416. const result = word.shiftRight( 22 ).bitXor( word );
  19417. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19418. } );
  19419. /** @module MathUtils **/
  19420. /**
  19421. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19422. * The corners are mapped to `0` and the center to `1`.
  19423. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19424. *
  19425. * @method
  19426. * @param {Node<float>} x - The value to remap.
  19427. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19428. * @return {Node<float>} The remapped value.
  19429. */
  19430. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19431. /**
  19432. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19433. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19434. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19435. *
  19436. * @method
  19437. * @param {Node<float>} x - The value to remap.
  19438. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19439. * @return {Node<float>} The remapped value.
  19440. */
  19441. 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 ) );
  19442. /**
  19443. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19444. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19445. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19446. *
  19447. * @method
  19448. * @param {Node<float>} x - The value to remap.
  19449. * @param {Node<float>} a - First control parameter.
  19450. * @param {Node<float>} b - Second control parameter.
  19451. * @return {Node<float>} The remapped value.
  19452. */
  19453. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19454. /**
  19455. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19456. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19457. *
  19458. * @method
  19459. * @param {Node<float>} x - The value to compute the sin for.
  19460. * @param {Node<float>} k - Controls the amount of bounces.
  19461. * @return {Node<float>} The result value.
  19462. */
  19463. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19464. // https://github.com/cabbibo/glsl-tri-noise-3d
  19465. /** @module TriNoise3D **/
  19466. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19467. return x.fract().sub( .5 ).abs();
  19468. } ).setLayout( {
  19469. name: 'tri',
  19470. type: 'float',
  19471. inputs: [
  19472. { name: 'x', type: 'float' }
  19473. ]
  19474. } );
  19475. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19476. 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. ) ) ) ) );
  19477. } ).setLayout( {
  19478. name: 'tri3',
  19479. type: 'vec3',
  19480. inputs: [
  19481. { name: 'p', type: 'vec3' }
  19482. ]
  19483. } );
  19484. /**
  19485. * Generates a noise value from the given position, speed and time parameters.
  19486. *
  19487. * @method
  19488. * @param {Node<vec3>} position - The position.
  19489. * @param {Node<float>} speed - The speed.
  19490. * @param {Node<float>} time - The time.
  19491. * @return {Node<float>} The generated noise.
  19492. */
  19493. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19494. const p = vec3( position ).toVar();
  19495. const z = float( 1.4 ).toVar();
  19496. const rz = float( 0.0 ).toVar();
  19497. const bp = vec3( p ).toVar();
  19498. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19499. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19500. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19501. bp.mulAssign( 1.8 );
  19502. z.mulAssign( 1.5 );
  19503. p.mulAssign( 1.2 );
  19504. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19505. rz.addAssign( t.div( z ) );
  19506. bp.addAssign( 0.14 );
  19507. } );
  19508. return rz;
  19509. } ).setLayout( {
  19510. name: 'triNoise3D',
  19511. type: 'float',
  19512. inputs: [
  19513. { name: 'position', type: 'vec3' },
  19514. { name: 'speed', type: 'float' },
  19515. { name: 'time', type: 'float' }
  19516. ]
  19517. } );
  19518. /** @module FunctionOverloadingNode **/
  19519. /**
  19520. * This class allows to define multiple overloaded versions
  19521. * of the same function. Depending on the parameters of the function
  19522. * call, the node picks the best-fit overloaded version.
  19523. *
  19524. * @augments Node
  19525. */
  19526. class FunctionOverloadingNode extends Node {
  19527. static get type() {
  19528. return 'FunctionOverloadingNode';
  19529. }
  19530. /**
  19531. * Constructs a new function overloading node.
  19532. *
  19533. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19534. * @param {...Node} parametersNodes - A list of parameter nodes.
  19535. */
  19536. constructor( functionNodes = [], ...parametersNodes ) {
  19537. super();
  19538. /**
  19539. * Array of `Fn` function definitions.
  19540. *
  19541. * @type {Array<Function>}
  19542. */
  19543. this.functionNodes = functionNodes;
  19544. /**
  19545. * A list of parameter nodes.
  19546. *
  19547. * @type {Array<Node>}
  19548. */
  19549. this.parametersNodes = parametersNodes;
  19550. /**
  19551. * The selected overloaded function call.
  19552. *
  19553. * @private
  19554. * @type {ShaderCallNodeInternal}
  19555. */
  19556. this._candidateFnCall = null;
  19557. /**
  19558. * This node is marked as global.
  19559. *
  19560. * @type {Boolean}
  19561. * @default true
  19562. */
  19563. this.global = true;
  19564. }
  19565. /**
  19566. * This method is overwritten since the node type is inferred from
  19567. * the function's return type.
  19568. *
  19569. * @param {NodeBuilder} builder - The current node builder.
  19570. * @return {String} The node type.
  19571. */
  19572. getNodeType() {
  19573. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19574. }
  19575. setup( builder ) {
  19576. const params = this.parametersNodes;
  19577. let candidateFnCall = this._candidateFnCall;
  19578. if ( candidateFnCall === null ) {
  19579. let candidateFn = null;
  19580. let candidateScore = -1;
  19581. for ( const functionNode of this.functionNodes ) {
  19582. const shaderNode = functionNode.shaderNode;
  19583. const layout = shaderNode.layout;
  19584. if ( layout === null ) {
  19585. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19586. }
  19587. const inputs = layout.inputs;
  19588. if ( params.length === inputs.length ) {
  19589. let score = 0;
  19590. for ( let i = 0; i < params.length; i ++ ) {
  19591. const param = params[ i ];
  19592. const input = inputs[ i ];
  19593. if ( param.getNodeType( builder ) === input.type ) {
  19594. score ++;
  19595. } else {
  19596. score = 0;
  19597. }
  19598. }
  19599. if ( score > candidateScore ) {
  19600. candidateFn = functionNode;
  19601. candidateScore = score;
  19602. }
  19603. }
  19604. }
  19605. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19606. }
  19607. return candidateFnCall;
  19608. }
  19609. }
  19610. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19611. /**
  19612. * TSL function for creating a function overloading node.
  19613. *
  19614. * @function
  19615. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19616. * @returns {FunctionOverloadingNode}
  19617. */
  19618. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19619. /** @module Timer **/
  19620. /**
  19621. * Represents the elapsed time in seconds.
  19622. *
  19623. * @type {UniformNode<float>}
  19624. */
  19625. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19626. /**
  19627. * Represents the delta time in seconds.
  19628. *
  19629. * @type {UniformNode<float>}
  19630. */
  19631. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19632. /**
  19633. * Represents the current frame ID.
  19634. *
  19635. * @type {UniformNode<uint>}
  19636. */
  19637. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19638. // Deprecated
  19639. /**
  19640. * @function
  19641. * @deprecated since r170. Use {@link time} instead.
  19642. *
  19643. * @param {Number} [timeScale=1] - The time scale.
  19644. * @returns {UniformNode<float>}
  19645. */
  19646. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19647. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19648. return time.mul( timeScale );
  19649. };
  19650. /**
  19651. * @function
  19652. * @deprecated since r170. Use {@link time} instead.
  19653. *
  19654. * @param {Number} [timeScale=1] - The time scale.
  19655. * @returns {UniformNode<float>}
  19656. */
  19657. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19658. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19659. return time.mul( timeScale );
  19660. };
  19661. /**
  19662. * @function
  19663. * @deprecated since r170. Use {@link deltaTime} instead.
  19664. *
  19665. * @param {Number} [timeScale=1] - The time scale.
  19666. * @returns {UniformNode<float>}
  19667. */
  19668. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19669. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19670. return deltaTime.mul( timeScale );
  19671. };
  19672. /** @module Oscillators **/
  19673. /**
  19674. * Generates a sine wave oscillation based on a timer.
  19675. *
  19676. * @method
  19677. * @param {Node<float>} t - The timer to generate the oscillation with.
  19678. * @return {Node<float>} The oscillation node.
  19679. */
  19680. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19681. /**
  19682. * Generates a square wave oscillation based on a timer.
  19683. *
  19684. * @method
  19685. * @param {Node<float>} t - The timer to generate the oscillation with.
  19686. * @return {Node<float>} The oscillation node.
  19687. */
  19688. const oscSquare = ( t = time ) => t.fract().round();
  19689. /**
  19690. * Generates a triangle wave oscillation based on a timer.
  19691. *
  19692. * @method
  19693. * @param {Node<float>} t - The timer to generate the oscillation with.
  19694. * @return {Node<float>} The oscillation node.
  19695. */
  19696. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19697. /**
  19698. * Generates a sawtooth wave oscillation based on a timer.
  19699. *
  19700. * @method
  19701. * @param {Node<float>} t - The timer to generate the oscillation with.
  19702. * @return {Node<float>} The oscillation node.
  19703. */
  19704. const oscSawtooth = ( t = time ) => t.fract();
  19705. /** @module UVUtils **/
  19706. /**
  19707. * Rotates the given uv coordinates around a center point
  19708. *
  19709. * @method
  19710. * @param {Node<vec2>} uv - The uv coordinates.
  19711. * @param {Node<float>} rotation - The rotation defined in radians.
  19712. * @param {Node<vec2>} center - The center of rotation
  19713. * @return {Node<vec2>} The rotated uv coordinates.
  19714. */
  19715. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19716. return rotate( uv.sub( center ), rotation ).add( center );
  19717. } );
  19718. /**
  19719. * Applies a spherical warping effect to the given uv coordinates.
  19720. *
  19721. * @method
  19722. * @param {Node<vec2>} uv - The uv coordinates.
  19723. * @param {Node<float>} strength - The strength of the effect.
  19724. * @param {Node<vec2>} center - The center point
  19725. * @return {Node<vec2>} The updated uv coordinates.
  19726. */
  19727. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19728. const delta = uv.sub( center );
  19729. const delta2 = delta.dot( delta );
  19730. const delta4 = delta2.mul( delta2 );
  19731. const deltaOffset = delta4.mul( strength );
  19732. return uv.add( delta.mul( deltaOffset ) );
  19733. } );
  19734. /** @module SpriteUtils **/
  19735. /**
  19736. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19737. * oriented always towards the camera.
  19738. *
  19739. * ```js
  19740. * material.vertexNode = billboarding();
  19741. * ```
  19742. *
  19743. * @method
  19744. * @param {Object} config - The configuration object.
  19745. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19746. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19747. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19748. * @return {Node<vec3>} The updated vertex position in clip space.
  19749. */
  19750. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19751. let worldMatrix;
  19752. if ( position !== null ) {
  19753. worldMatrix = modelWorldMatrix.toVar();
  19754. worldMatrix[ 3 ][ 0 ] = position.x;
  19755. worldMatrix[ 3 ][ 1 ] = position.y;
  19756. worldMatrix[ 3 ][ 2 ] = position.z;
  19757. } else {
  19758. worldMatrix = modelWorldMatrix;
  19759. }
  19760. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19761. if ( defined( horizontal ) ) {
  19762. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19763. modelViewMatrix[ 0 ][ 1 ] = 0;
  19764. modelViewMatrix[ 0 ][ 2 ] = 0;
  19765. }
  19766. if ( defined( vertical ) ) {
  19767. modelViewMatrix[ 1 ][ 0 ] = 0;
  19768. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19769. modelViewMatrix[ 1 ][ 2 ] = 0;
  19770. }
  19771. modelViewMatrix[ 2 ][ 0 ] = 0;
  19772. modelViewMatrix[ 2 ][ 1 ] = 0;
  19773. modelViewMatrix[ 2 ][ 2 ] = 1;
  19774. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19775. } );
  19776. /** @module ViewportUtils **/
  19777. /**
  19778. * A special version of a screen uv function that involves a depth comparison
  19779. * when computing the final uvs. The function mitigates visual errors when
  19780. * using viewport texture nodes for refraction purposes. Without this function
  19781. * objects in front of a refractive surface might appear on the refractive surface
  19782. * which is incorrect.
  19783. *
  19784. * @method
  19785. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19786. * @return {Node<vec2>} The update uv coordinates.
  19787. */
  19788. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19789. const depth = linearDepth();
  19790. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19791. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19792. return finalUV;
  19793. } );
  19794. /** @module SpriteSheetUVNode **/
  19795. /**
  19796. * Can be used to compute texture coordinates for animated sprite sheets.
  19797. *
  19798. * ```js
  19799. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19800. *
  19801. * material.colorNode = texture( spriteSheet, uvNode );
  19802. * ```
  19803. *
  19804. * @augments Node
  19805. */
  19806. class SpriteSheetUVNode extends Node {
  19807. static get type() {
  19808. return 'SpriteSheetUVNode';
  19809. }
  19810. /**
  19811. * Constructs a new sprite sheet uv node.
  19812. *
  19813. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19814. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19815. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19816. */
  19817. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19818. super( 'vec2' );
  19819. /**
  19820. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19821. *
  19822. * @type {Node<vec2>}
  19823. */
  19824. this.countNode = countNode;
  19825. /**
  19826. * The uv node.
  19827. *
  19828. * @type {Node<vec2>}
  19829. */
  19830. this.uvNode = uvNode;
  19831. /**
  19832. * The node that defines the current frame/sprite.
  19833. *
  19834. * @type {Node<float>}
  19835. */
  19836. this.frameNode = frameNode;
  19837. }
  19838. setup() {
  19839. const { frameNode, uvNode, countNode } = this;
  19840. const { width, height } = countNode;
  19841. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19842. const column = frameNum.mod( width );
  19843. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19844. const scale = countNode.reciprocal();
  19845. const uvFrameOffset = vec2( column, row );
  19846. return uvNode.add( uvFrameOffset ).mul( scale );
  19847. }
  19848. }
  19849. /**
  19850. * TSL function for creating a sprite sheet uv node.
  19851. *
  19852. * @function
  19853. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19854. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19855. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19856. * @returns {SpriteSheetUVNode}
  19857. */
  19858. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19859. /** @module TriplanarTexturesNode **/
  19860. /**
  19861. * Can be used for triplanar texture mapping.
  19862. *
  19863. * ```js
  19864. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19865. * ```
  19866. *
  19867. * @augments Node
  19868. */
  19869. class TriplanarTexturesNode extends Node {
  19870. static get type() {
  19871. return 'TriplanarTexturesNode';
  19872. }
  19873. /**
  19874. * Constructs a new triplanar textures node.
  19875. *
  19876. * @param {Node} textureXNode - First texture node.
  19877. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19878. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19879. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19880. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19881. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19882. */
  19883. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19884. super( 'vec4' );
  19885. /**
  19886. * First texture node.
  19887. *
  19888. * @type {Node}
  19889. */
  19890. this.textureXNode = textureXNode;
  19891. /**
  19892. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19893. *
  19894. * @type {Node}
  19895. * @default null
  19896. */
  19897. this.textureYNode = textureYNode;
  19898. /**
  19899. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19900. *
  19901. * @type {Node}
  19902. * @default null
  19903. */
  19904. this.textureZNode = textureZNode;
  19905. /**
  19906. * The scale node.
  19907. *
  19908. * @type {Node<float>}
  19909. * @default float(1)
  19910. */
  19911. this.scaleNode = scaleNode;
  19912. /**
  19913. * Vertex positions in local space.
  19914. *
  19915. * @type {Node<vec3>}
  19916. * @default positionLocal
  19917. */
  19918. this.positionNode = positionNode;
  19919. /**
  19920. * Normals in local space.
  19921. *
  19922. * @type {Node<vec3>}
  19923. * @default normalLocal
  19924. */
  19925. this.normalNode = normalNode;
  19926. }
  19927. setup() {
  19928. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19929. // Ref: https://github.com/keijiro/StandardTriplanar
  19930. // Blending factor of triplanar mapping
  19931. let bf = normalNode.abs().normalize();
  19932. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19933. // Triplanar mapping
  19934. const tx = positionNode.yz.mul( scaleNode );
  19935. const ty = positionNode.zx.mul( scaleNode );
  19936. const tz = positionNode.xy.mul( scaleNode );
  19937. // Base color
  19938. const textureX = textureXNode.value;
  19939. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19940. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19941. const cx = texture( textureX, tx ).mul( bf.x );
  19942. const cy = texture( textureY, ty ).mul( bf.y );
  19943. const cz = texture( textureZ, tz ).mul( bf.z );
  19944. return add( cx, cy, cz );
  19945. }
  19946. }
  19947. /**
  19948. * TSL function for creating a triplanar textures node.
  19949. *
  19950. * @function
  19951. * @param {Node} textureXNode - First texture node.
  19952. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19953. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19954. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19955. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19956. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19957. * @returns {TriplanarTexturesNode}
  19958. */
  19959. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19960. /**
  19961. * TSL function for creating a triplanar textures node.
  19962. *
  19963. * @function
  19964. * @param {Node} textureXNode - First texture node.
  19965. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19966. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19967. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19968. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19969. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19970. * @returns {TriplanarTexturesNode}
  19971. */
  19972. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19973. /** @module ReflectorNode **/
  19974. const _reflectorPlane = new Plane();
  19975. const _normal = new Vector3();
  19976. const _reflectorWorldPosition = new Vector3();
  19977. const _cameraWorldPosition = new Vector3();
  19978. const _rotationMatrix = new Matrix4();
  19979. const _lookAtPosition = new Vector3( 0, 0, -1 );
  19980. const clipPlane = new Vector4();
  19981. const _view = new Vector3();
  19982. const _target = new Vector3();
  19983. const _q = new Vector4();
  19984. const _size$2 = new Vector2();
  19985. const _defaultRT = new RenderTarget();
  19986. const _defaultUV = screenUV.flipX();
  19987. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19988. let _inReflector = false;
  19989. /**
  19990. * This node can be used to implement mirror-like flat reflective surfaces.
  19991. *
  19992. * ```js
  19993. * const groundReflector = reflector();
  19994. * material.colorNode = groundReflector;
  19995. *
  19996. * const plane = new Mesh( geometry, material );
  19997. * plane.add( groundReflector.target );
  19998. * ```
  19999. *
  20000. * @augments module:TextureNode~TextureNode
  20001. */
  20002. class ReflectorNode extends TextureNode {
  20003. static get type() {
  20004. return 'ReflectorNode';
  20005. }
  20006. /**
  20007. * Constructs a new reflector node.
  20008. *
  20009. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20010. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20011. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20012. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20013. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20014. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20015. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20016. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20017. */
  20018. constructor( parameters = {} ) {
  20019. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20020. /**
  20021. * A reference to the internal reflector base node which holds the actual implementation.
  20022. *
  20023. * @private
  20024. * @type {ReflectorBaseNode?}
  20025. * @default null
  20026. */
  20027. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20028. /**
  20029. * A reference to the internal depth node.
  20030. *
  20031. * @private
  20032. * @type {Node?}
  20033. * @default null
  20034. */
  20035. this._depthNode = null;
  20036. this.setUpdateMatrix( false );
  20037. }
  20038. /**
  20039. * A reference to the internal reflector node.
  20040. *
  20041. * @type {ReflectorBaseNode}
  20042. */
  20043. get reflector() {
  20044. return this._reflectorBaseNode;
  20045. }
  20046. /**
  20047. * A reference to 3D object the reflector is linked to.
  20048. *
  20049. * @type {Object3D}
  20050. */
  20051. get target() {
  20052. return this._reflectorBaseNode.target;
  20053. }
  20054. /**
  20055. * Returns a node representing the mirror's depth. That can be used
  20056. * to implement more advanced reflection effects like distance attenuation.
  20057. *
  20058. * @return {Node} The depth node.
  20059. */
  20060. getDepthNode() {
  20061. if ( this._depthNode === null ) {
  20062. if ( this._reflectorBaseNode.depth !== true ) {
  20063. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20064. }
  20065. this._depthNode = nodeObject( new ReflectorNode( {
  20066. defaultTexture: _defaultRT.depthTexture,
  20067. reflector: this._reflectorBaseNode
  20068. } ) );
  20069. }
  20070. return this._depthNode;
  20071. }
  20072. setup( builder ) {
  20073. // ignore if used in post-processing
  20074. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20075. return super.setup( builder );
  20076. }
  20077. clone() {
  20078. const texture = new this.constructor( this.reflectorNode );
  20079. texture._reflectorBaseNode = this._reflectorBaseNode;
  20080. return texture;
  20081. }
  20082. }
  20083. /**
  20084. * Holds the actual implementation of the reflector.
  20085. *
  20086. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20087. * in `ReflectorNode`, see #29619.
  20088. *
  20089. * @private
  20090. * @augments Node
  20091. */
  20092. class ReflectorBaseNode extends Node {
  20093. static get type() {
  20094. return 'ReflectorBaseNode';
  20095. }
  20096. /**
  20097. * Constructs a new reflector base node.
  20098. *
  20099. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20100. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20101. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20102. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20103. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20104. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20105. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20106. */
  20107. constructor( textureNode, parameters = {} ) {
  20108. super();
  20109. const {
  20110. target = new Object3D(),
  20111. resolution = 1,
  20112. generateMipmaps = false,
  20113. bounces = true,
  20114. depth = false
  20115. } = parameters;
  20116. /**
  20117. * Represents the rendered reflections as a texture node.
  20118. *
  20119. * @type {TextureNode}
  20120. */
  20121. this.textureNode = textureNode;
  20122. /**
  20123. * The 3D object the reflector is linked to.
  20124. *
  20125. * @type {Object3D}
  20126. * @default {new Object3D()}
  20127. */
  20128. this.target = target;
  20129. /**
  20130. * The resolution scale.
  20131. *
  20132. * @type {Number}
  20133. * @default {1}
  20134. */
  20135. this.resolution = resolution;
  20136. /**
  20137. * Whether mipmaps should be generated or not.
  20138. *
  20139. * @type {Boolean}
  20140. * @default {false}
  20141. */
  20142. this.generateMipmaps = generateMipmaps;
  20143. /**
  20144. * Whether reflectors can render other reflector nodes or not.
  20145. *
  20146. * @type {Boolean}
  20147. * @default {true}
  20148. */
  20149. this.bounces = bounces;
  20150. /**
  20151. * Whether depth data should be generated or not.
  20152. *
  20153. * @type {Boolean}
  20154. * @default {false}
  20155. */
  20156. this.depth = depth;
  20157. /**
  20158. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20159. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20160. *
  20161. * @type {String}
  20162. * @default 'render'
  20163. */
  20164. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20165. /**
  20166. * Weak map for managing virtual cameras.
  20167. *
  20168. * @type {WeakMap<Camera, Camera>}
  20169. */
  20170. this.virtualCameras = new WeakMap();
  20171. /**
  20172. * Weak map for managing render targets.
  20173. *
  20174. * @type {WeakMap<Camera, RenderTarget>}
  20175. */
  20176. this.renderTargets = new WeakMap();
  20177. }
  20178. /**
  20179. * Updates the resolution of the internal render target.
  20180. *
  20181. * @private
  20182. * @param {RenderTarget} renderTarget - The render target to resize.
  20183. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20184. */
  20185. _updateResolution( renderTarget, renderer ) {
  20186. const resolution = this.resolution;
  20187. renderer.getDrawingBufferSize( _size$2 );
  20188. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20189. }
  20190. setup( builder ) {
  20191. this._updateResolution( _defaultRT, builder.renderer );
  20192. return super.setup( builder );
  20193. }
  20194. /**
  20195. * Returns a virtual camera for the given camera. The virtual camera is used to
  20196. * render the scene from the reflector's view so correct reflections can be produced.
  20197. *
  20198. * @param {Camera} camera - The scene's camera.
  20199. * @return {Camera} The corresponding virtual camera.
  20200. */
  20201. getVirtualCamera( camera ) {
  20202. let virtualCamera = this.virtualCameras.get( camera );
  20203. if ( virtualCamera === undefined ) {
  20204. virtualCamera = camera.clone();
  20205. this.virtualCameras.set( camera, virtualCamera );
  20206. }
  20207. return virtualCamera;
  20208. }
  20209. /**
  20210. * Returns a render target for the given camera. The reflections are rendered
  20211. * into this render target.
  20212. *
  20213. * @param {Camera} camera - The scene's camera.
  20214. * @return {RenderTarget} The render target.
  20215. */
  20216. getRenderTarget( camera ) {
  20217. let renderTarget = this.renderTargets.get( camera );
  20218. if ( renderTarget === undefined ) {
  20219. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20220. if ( this.generateMipmaps === true ) {
  20221. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20222. renderTarget.texture.generateMipmaps = true;
  20223. }
  20224. if ( this.depth === true ) {
  20225. renderTarget.depthTexture = new DepthTexture();
  20226. }
  20227. this.renderTargets.set( camera, renderTarget );
  20228. }
  20229. return renderTarget;
  20230. }
  20231. updateBefore( frame ) {
  20232. if ( this.bounces === false && _inReflector ) return false;
  20233. _inReflector = true;
  20234. const { scene, camera, renderer, material } = frame;
  20235. const { target } = this;
  20236. const virtualCamera = this.getVirtualCamera( camera );
  20237. const renderTarget = this.getRenderTarget( virtualCamera );
  20238. renderer.getDrawingBufferSize( _size$2 );
  20239. this._updateResolution( renderTarget, renderer );
  20240. //
  20241. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20242. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20243. _rotationMatrix.extractRotation( target.matrixWorld );
  20244. _normal.set( 0, 0, 1 );
  20245. _normal.applyMatrix4( _rotationMatrix );
  20246. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20247. // Avoid rendering when reflector is facing away
  20248. if ( _view.dot( _normal ) > 0 ) return;
  20249. _view.reflect( _normal ).negate();
  20250. _view.add( _reflectorWorldPosition );
  20251. _rotationMatrix.extractRotation( camera.matrixWorld );
  20252. _lookAtPosition.set( 0, 0, -1 );
  20253. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20254. _lookAtPosition.add( _cameraWorldPosition );
  20255. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20256. _target.reflect( _normal ).negate();
  20257. _target.add( _reflectorWorldPosition );
  20258. //
  20259. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20260. virtualCamera.position.copy( _view );
  20261. virtualCamera.up.set( 0, 1, 0 );
  20262. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20263. virtualCamera.up.reflect( _normal );
  20264. virtualCamera.lookAt( _target );
  20265. virtualCamera.near = camera.near;
  20266. virtualCamera.far = camera.far;
  20267. virtualCamera.updateMatrixWorld();
  20268. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20269. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20270. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20271. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20272. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20273. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20274. const projectionMatrix = virtualCamera.projectionMatrix;
  20275. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20276. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20277. _q.z = -1;
  20278. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20279. // Calculate the scaled plane vector
  20280. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20281. const clipBias = 0;
  20282. // Replacing the third row of the projection matrix
  20283. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20284. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20285. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20286. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20287. //
  20288. this.textureNode.value = renderTarget.texture;
  20289. if ( this.depth === true ) {
  20290. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20291. }
  20292. material.visible = false;
  20293. const currentRenderTarget = renderer.getRenderTarget();
  20294. const currentMRT = renderer.getMRT();
  20295. const currentAutoClear = renderer.autoClear;
  20296. renderer.setMRT( null );
  20297. renderer.setRenderTarget( renderTarget );
  20298. renderer.autoClear = true;
  20299. renderer.render( scene, virtualCamera );
  20300. renderer.setMRT( currentMRT );
  20301. renderer.setRenderTarget( currentRenderTarget );
  20302. renderer.autoClear = currentAutoClear;
  20303. material.visible = true;
  20304. _inReflector = false;
  20305. }
  20306. }
  20307. /**
  20308. * TSL function for creating a reflector node.
  20309. *
  20310. * @function
  20311. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20312. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20313. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20314. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20315. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20316. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20317. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20318. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20319. * @returns {ReflectorNode}
  20320. */
  20321. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20322. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  20323. /**
  20324. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20325. *
  20326. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20327. *
  20328. * @private
  20329. * @augments BufferGeometry
  20330. */
  20331. class QuadGeometry extends BufferGeometry {
  20332. /**
  20333. * Constructs a new quad geometry.
  20334. *
  20335. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20336. */
  20337. constructor( flipY = false ) {
  20338. super();
  20339. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20340. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  20341. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20342. }
  20343. }
  20344. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20345. /**
  20346. * This module is a helper for passes which need to render a full
  20347. * screen effect which is quite common in context of post processing.
  20348. *
  20349. * The intended usage is to reuse a single quad mesh for rendering
  20350. * subsequent passes by just reassigning the `material` reference.
  20351. *
  20352. * @augments Mesh
  20353. */
  20354. class QuadMesh extends Mesh {
  20355. /**
  20356. * Constructs a new quad mesh.
  20357. *
  20358. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20359. */
  20360. constructor( material = null ) {
  20361. super( _geometry, material );
  20362. /**
  20363. * The camera to render the quad mesh with.
  20364. *
  20365. * @type {OrthographicCamera}
  20366. * @readonly
  20367. */
  20368. this.camera = _camera;
  20369. /**
  20370. * This flag can be used for type testing.
  20371. *
  20372. * @type {Boolean}
  20373. * @readonly
  20374. * @default true
  20375. */
  20376. this.isQuadMesh = true;
  20377. }
  20378. /**
  20379. * Async version of `render()`.
  20380. *
  20381. * @async
  20382. * @param {Renderer} renderer - The renderer.
  20383. * @return {Promise} A Promise that resolves when the render has been finished.
  20384. */
  20385. async renderAsync( renderer ) {
  20386. return renderer.renderAsync( this, _camera );
  20387. }
  20388. /**
  20389. * Renders the quad mesh
  20390. *
  20391. * @param {Renderer} renderer - The renderer.
  20392. */
  20393. render( renderer ) {
  20394. renderer.render( this, _camera );
  20395. }
  20396. }
  20397. /** @module RTTNode **/
  20398. const _size$1 = /*@__PURE__*/ new Vector2();
  20399. /**
  20400. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20401. * This module is especially relevant in context of post processing where certain nodes require
  20402. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20403. * on this module, the node system can automatically ensure texture input if required.
  20404. *
  20405. * @augments module:TextureNode~TextureNode
  20406. */
  20407. class RTTNode extends TextureNode {
  20408. static get type() {
  20409. return 'RTTNode';
  20410. }
  20411. /**
  20412. * Constructs a new RTT node.
  20413. *
  20414. * @param {Node} node - The node to render a texture with.
  20415. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20416. * @param {Number?} [height=null] - The height of the internal render target.
  20417. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20418. */
  20419. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20420. const renderTarget = new RenderTarget( width, height, options );
  20421. super( renderTarget.texture, uv() );
  20422. /**
  20423. * The node to render a texture with.
  20424. *
  20425. * @type {Node}
  20426. */
  20427. this.node = node;
  20428. /**
  20429. * The width of the internal render target.
  20430. * If not width is applied, the render target is automatically resized.
  20431. *
  20432. * @type {Number?}
  20433. * @default null
  20434. */
  20435. this.width = width;
  20436. /**
  20437. * The height of the internal render target.
  20438. *
  20439. * @type {Number?}
  20440. * @default null
  20441. */
  20442. this.height = height;
  20443. /**
  20444. * The pixel ratio
  20445. *
  20446. * @type {Number}
  20447. * @default 1
  20448. */
  20449. this.pixelRatio = 1;
  20450. /**
  20451. * The render target
  20452. *
  20453. * @type {RenderTarget}
  20454. */
  20455. this.renderTarget = renderTarget;
  20456. /**
  20457. * Whether the texture requires an update or not.
  20458. *
  20459. * @type {Boolean}
  20460. * @default true
  20461. */
  20462. this.textureNeedsUpdate = true;
  20463. /**
  20464. * Whether the texture should automatically be updated or not.
  20465. *
  20466. * @type {Boolean}
  20467. * @default true
  20468. */
  20469. this.autoUpdate = true;
  20470. /**
  20471. * The node which is used with the quad mesh for RTT.
  20472. *
  20473. * @private
  20474. * @type {Node}
  20475. * @default null
  20476. */
  20477. this._rttNode = null;
  20478. /**
  20479. * The internal quad mesh for RTT.
  20480. *
  20481. * @private
  20482. * @type {QuadMesh}
  20483. */
  20484. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20485. /**
  20486. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20487. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20488. *
  20489. * @type {String}
  20490. * @default 'render'
  20491. */
  20492. this.updateBeforeType = NodeUpdateType.RENDER;
  20493. }
  20494. /**
  20495. * Whether the internal render target should automatically be resized or not.
  20496. *
  20497. * @type {Boolean}
  20498. * @readonly
  20499. * @default true
  20500. */
  20501. get autoSize() {
  20502. return this.width === null;
  20503. }
  20504. setup( builder ) {
  20505. this._rttNode = this.node.context( builder.getSharedContext() );
  20506. this._quadMesh.material.name = 'RTT';
  20507. this._quadMesh.material.needsUpdate = true;
  20508. return super.setup( builder );
  20509. }
  20510. /**
  20511. * Sets the size of the internal render target
  20512. *
  20513. * @param {Number} width - The width to set.
  20514. * @param {Number} height - The width to set.
  20515. */
  20516. setSize( width, height ) {
  20517. this.width = width;
  20518. this.height = height;
  20519. const effectiveWidth = width * this.pixelRatio;
  20520. const effectiveHeight = height * this.pixelRatio;
  20521. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20522. this.textureNeedsUpdate = true;
  20523. }
  20524. /**
  20525. * Sets the pixel ratio. This will also resize the render target.
  20526. *
  20527. * @param {Number} pixelRatio - The pixel ratio to set.
  20528. */
  20529. setPixelRatio( pixelRatio ) {
  20530. this.pixelRatio = pixelRatio;
  20531. this.setSize( this.width, this.height );
  20532. }
  20533. updateBefore( { renderer } ) {
  20534. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20535. this.textureNeedsUpdate = false;
  20536. //
  20537. if ( this.autoSize === true ) {
  20538. this.pixelRatio = renderer.getPixelRatio();
  20539. const size = renderer.getSize( _size$1 );
  20540. this.setSize( size.width, size.height );
  20541. }
  20542. //
  20543. this._quadMesh.material.fragmentNode = this._rttNode;
  20544. //
  20545. const currentRenderTarget = renderer.getRenderTarget();
  20546. renderer.setRenderTarget( this.renderTarget );
  20547. this._quadMesh.render( renderer );
  20548. renderer.setRenderTarget( currentRenderTarget );
  20549. }
  20550. clone() {
  20551. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20552. newNode.sampler = this.sampler;
  20553. newNode.referenceNode = this;
  20554. return newNode;
  20555. }
  20556. }
  20557. /**
  20558. * TSL function for creating a RTT node.
  20559. *
  20560. * @function
  20561. * @param {Node} node - The node to render a texture with.
  20562. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20563. * @param {Number?} [height=null] - The height of the internal render target.
  20564. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20565. * @returns {RTTNode}
  20566. */
  20567. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20568. /**
  20569. * TSL function for converting nodes to textures nodes.
  20570. *
  20571. * @function
  20572. * @param {Node} node - The node to render a texture with.
  20573. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20574. * @param {Number?} [height=null] - The height of the internal render target.
  20575. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20576. * @returns {RTTNode}
  20577. */
  20578. const convertToTexture = ( node, ...params ) => {
  20579. if ( node.isTextureNode ) return node;
  20580. if ( node.isPassNode ) return node.getTextureNode();
  20581. return rtt( node, ...params );
  20582. };
  20583. /** @module PostProcessingUtils **/
  20584. /**
  20585. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20586. * depth value and the camera's inverse projection matrix.
  20587. *
  20588. * @method
  20589. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20590. * @param {Node<float>} depth - The fragment's depth value.
  20591. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20592. * @return {Node<vec3>} The fragments position in view space.
  20593. */
  20594. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20595. let clipSpacePosition;
  20596. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20597. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20598. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20599. } else {
  20600. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20601. }
  20602. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20603. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20604. } );
  20605. /**
  20606. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20607. * and the camera's projection matrix
  20608. *
  20609. * @method
  20610. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20611. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20612. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20613. */
  20614. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20615. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20616. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20617. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20618. } );
  20619. /**
  20620. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20621. * target is available or if flat surface normals are required.
  20622. *
  20623. * @method
  20624. * @param {Node<vec2>} uv - The texture coordinate.
  20625. * @param {DepthTexture} depthTexture - The depth texture.
  20626. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20627. * @return {Node<vec3>} The computed normal vector.
  20628. */
  20629. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20630. const size = textureSize( textureLoad( depthTexture ) );
  20631. const p = ivec2( uv.mul( size ) ).toVar();
  20632. const c0 = textureLoad( depthTexture, p ).toVar();
  20633. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20634. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20635. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20636. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20637. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20638. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20639. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20640. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20641. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20642. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20643. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20644. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20645. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20646. 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 ) ) );
  20647. 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 ) ) );
  20648. return normalize( cross( dpdx, dpdy ) );
  20649. } );
  20650. /**
  20651. * This special type of instanced buffer attribute is intended for compute shaders.
  20652. * In earlier three.js versions it was only possible to update attribute data
  20653. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20654. * new material system and renderer it is now possible to use compute shaders
  20655. * to compute the data for an attribute more efficiently on the GPU.
  20656. *
  20657. * The idea is to create an instance of this class and provide it as an input
  20658. * to {@link module:StorageBufferNode}.
  20659. *
  20660. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20661. *
  20662. * @augments InstancedBufferAttribute
  20663. */
  20664. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20665. /**
  20666. * Constructs a new storage instanced buffer attribute.
  20667. *
  20668. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20669. * The subsequent parameters are then obsolete.
  20670. * @param {Number} itemSize - The item size.
  20671. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20672. */
  20673. constructor( count, itemSize, typeClass = Float32Array ) {
  20674. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20675. super( array, itemSize );
  20676. /**
  20677. * This flag can be used for type testing.
  20678. *
  20679. * @type {Boolean}
  20680. * @readonly
  20681. * @default true
  20682. */
  20683. this.isStorageInstancedBufferAttribute = true;
  20684. }
  20685. }
  20686. /**
  20687. * This special type of buffer attribute is intended for compute shaders.
  20688. * In earlier three.js versions it was only possible to update attribute data
  20689. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20690. * new material system and renderer it is now possible to use compute shaders
  20691. * to compute the data for an attribute more efficiently on the GPU.
  20692. *
  20693. * The idea is to create an instance of this class and provide it as an input
  20694. * to {@link module:StorageBufferNode}.
  20695. *
  20696. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20697. *
  20698. * @augments BufferAttribute
  20699. */
  20700. class StorageBufferAttribute extends BufferAttribute {
  20701. /**
  20702. * Constructs a new storage buffer attribute.
  20703. *
  20704. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20705. * The subsequent parameters are then obsolete.
  20706. * @param {Number} itemSize - The item size.
  20707. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20708. */
  20709. constructor( count, itemSize, typeClass = Float32Array ) {
  20710. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20711. super( array, itemSize );
  20712. /**
  20713. * This flag can be used for type testing.
  20714. *
  20715. * @type {Boolean}
  20716. * @readonly
  20717. * @default true
  20718. */
  20719. this.isStorageBufferAttribute = true;
  20720. }
  20721. }
  20722. /** @module StorageArrayElementNode **/
  20723. /**
  20724. * This class enables element access on instances of {@link StorageBufferNode}.
  20725. * In most cases, it is indirectly used when accessing elements with the
  20726. * {@link StorageBufferNode#element} method.
  20727. *
  20728. * ```js
  20729. * const position = positionStorage.element( instanceIndex );
  20730. * ```
  20731. *
  20732. * @augments ArrayElementNode
  20733. */
  20734. class StorageArrayElementNode extends ArrayElementNode {
  20735. static get type() {
  20736. return 'StorageArrayElementNode';
  20737. }
  20738. /**
  20739. * Constructs storage buffer element node.
  20740. *
  20741. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20742. * @param {Node} indexNode - The index node that defines the element access.
  20743. */
  20744. constructor( storageBufferNode, indexNode ) {
  20745. super( storageBufferNode, indexNode );
  20746. /**
  20747. * This flag can be used for type testing.
  20748. *
  20749. * @type {Boolean}
  20750. * @readonly
  20751. * @default true
  20752. */
  20753. this.isStorageArrayElementNode = true;
  20754. }
  20755. /**
  20756. * The storage buffer node.
  20757. *
  20758. * @param {Node} value
  20759. * @type {StorageBufferNode}
  20760. */
  20761. set storageBufferNode( value ) {
  20762. this.node = value;
  20763. }
  20764. get storageBufferNode() {
  20765. return this.node;
  20766. }
  20767. setup( builder ) {
  20768. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20769. if ( this.node.isPBO === true ) {
  20770. builder.setupPBO( this.node );
  20771. }
  20772. }
  20773. return super.setup( builder );
  20774. }
  20775. generate( builder, output ) {
  20776. let snippet;
  20777. const isAssignContext = builder.context.assign;
  20778. //
  20779. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20780. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20781. snippet = builder.generatePBO( this );
  20782. } else {
  20783. snippet = this.node.build( builder );
  20784. }
  20785. } else {
  20786. snippet = super.generate( builder );
  20787. }
  20788. if ( isAssignContext !== true ) {
  20789. const type = this.getNodeType( builder );
  20790. snippet = builder.format( snippet, type, output );
  20791. }
  20792. return snippet;
  20793. }
  20794. }
  20795. /**
  20796. * TSL function for creating a storage element node.
  20797. *
  20798. * @function
  20799. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20800. * @param {Node} indexNode - The index node that defines the element access.
  20801. * @returns {StorageArrayElementNode}
  20802. */
  20803. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20804. /** @module StorageBufferNode **/
  20805. /**
  20806. * This node is used in context of compute shaders and allows to define a
  20807. * storage buffer for data. A typical workflow is to create instances of
  20808. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20809. * setup up a compute shader that writes into the buffers and then convert
  20810. * the storage buffers to attribute nodes for rendering.
  20811. *
  20812. * ```js
  20813. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20814. *
  20815. * const computeInit = Fn( () => { // the compute shader
  20816. *
  20817. * const position = positionBuffer.element( instanceIndex );
  20818. *
  20819. * // compute position data
  20820. *
  20821. * position.x = 1;
  20822. * position.y = 1;
  20823. * position.z = 1;
  20824. *
  20825. * } )().compute( particleCount );
  20826. *
  20827. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20828. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20829. *
  20830. * renderer.computeAsync( computeInit );
  20831. *
  20832. * ```
  20833. *
  20834. * @augments BufferNode
  20835. */
  20836. class StorageBufferNode extends BufferNode {
  20837. static get type() {
  20838. return 'StorageBufferNode';
  20839. }
  20840. /**
  20841. * Constructs a new storage buffer node.
  20842. *
  20843. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20844. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20845. * @param {Number} [bufferCount=0] - The buffer count.
  20846. */
  20847. constructor( value, bufferType = null, bufferCount = 0 ) {
  20848. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20849. bufferType = getTypeFromLength( value.itemSize );
  20850. bufferCount = value.count;
  20851. }
  20852. super( value, bufferType, bufferCount );
  20853. /**
  20854. * This flag can be used for type testing.
  20855. *
  20856. * @type {Boolean}
  20857. * @readonly
  20858. * @default true
  20859. */
  20860. this.isStorageBufferNode = true;
  20861. /**
  20862. * The access type of the texture node.
  20863. *
  20864. * @type {String}
  20865. * @default 'readWrite'
  20866. */
  20867. this.access = NodeAccess.READ_WRITE;
  20868. /**
  20869. * Whether the node is atomic or not.
  20870. *
  20871. * @type {Boolean}
  20872. * @default false
  20873. */
  20874. this.isAtomic = false;
  20875. /**
  20876. * Whether the node represents a PBO or not.
  20877. * Only relevant for WebGL.
  20878. *
  20879. * @type {Boolean}
  20880. * @default false
  20881. */
  20882. this.isPBO = false;
  20883. /**
  20884. * A reference to the internal buffer attribute node.
  20885. *
  20886. * @type {BufferAttributeNode?}
  20887. * @default null
  20888. */
  20889. this._attribute = null;
  20890. /**
  20891. * A reference to the internal varying node.
  20892. *
  20893. * @type {VaryingNode?}
  20894. * @default null
  20895. */
  20896. this._varying = null;
  20897. /**
  20898. * `StorageBufferNode` sets this property to `true` by default.
  20899. *
  20900. * @type {Boolean}
  20901. * @default true
  20902. */
  20903. this.global = true;
  20904. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20905. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20906. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20907. else value.isStorageBufferAttribute = true;
  20908. }
  20909. }
  20910. /**
  20911. * This method is overwritten since the buffer data might be shared
  20912. * and thus the hash should be shared as well.
  20913. *
  20914. * @param {NodeBuilder} builder - The current node builder.
  20915. * @return {String} The hash.
  20916. */
  20917. getHash( builder ) {
  20918. if ( this.bufferCount === 0 ) {
  20919. let bufferData = builder.globalCache.getData( this.value );
  20920. if ( bufferData === undefined ) {
  20921. bufferData = {
  20922. node: this
  20923. };
  20924. builder.globalCache.setData( this.value, bufferData );
  20925. }
  20926. return bufferData.node.uuid;
  20927. }
  20928. return this.uuid;
  20929. }
  20930. /**
  20931. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20932. *
  20933. * @param {NodeBuilder} builder - The current node builder.
  20934. * @return {String} The input type.
  20935. */
  20936. getInputType( /*builder*/ ) {
  20937. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20938. }
  20939. /**
  20940. * Enables element access with the given index node.
  20941. *
  20942. * @param {IndexNode} indexNode - The index node.
  20943. * @return {StorageArrayElementNode} A node representing the element access.
  20944. */
  20945. element( indexNode ) {
  20946. return storageElement( this, indexNode );
  20947. }
  20948. /**
  20949. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20950. *
  20951. * @param {Boolean} value - The value so set.
  20952. * @return {StorageBufferNode} A reference to this node.
  20953. */
  20954. setPBO( value ) {
  20955. this.isPBO = value;
  20956. return this;
  20957. }
  20958. /**
  20959. * Returns the `isPBO` value.
  20960. *
  20961. * @return {Boolean} Whether the node represents a PBO or not.
  20962. */
  20963. getPBO() {
  20964. return this.isPBO;
  20965. }
  20966. /**
  20967. * Defines the node access.
  20968. *
  20969. * @param {String} value - The node access.
  20970. * @return {StorageBufferNode} A reference to this node.
  20971. */
  20972. setAccess( value ) {
  20973. this.access = value;
  20974. return this;
  20975. }
  20976. /**
  20977. * Convenience method for configuring a read-only node access.
  20978. *
  20979. * @return {StorageBufferNode} A reference to this node.
  20980. */
  20981. toReadOnly() {
  20982. return this.setAccess( NodeAccess.READ_ONLY );
  20983. }
  20984. /**
  20985. * Defines whether the node is atomic or not.
  20986. *
  20987. * @param {Boolean} value - The atomic flag.
  20988. * @return {StorageBufferNode} A reference to this node.
  20989. */
  20990. setAtomic( value ) {
  20991. this.isAtomic = value;
  20992. return this;
  20993. }
  20994. /**
  20995. * Convenience method for making this node atomic.
  20996. *
  20997. * @return {StorageBufferNode} A reference to this node.
  20998. */
  20999. toAtomic() {
  21000. return this.setAtomic( true );
  21001. }
  21002. /**
  21003. * Returns attribute data for this storage buffer node.
  21004. *
  21005. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21006. */
  21007. getAttributeData() {
  21008. if ( this._attribute === null ) {
  21009. this._attribute = bufferAttribute( this.value );
  21010. this._varying = varying( this._attribute );
  21011. }
  21012. return {
  21013. attribute: this._attribute,
  21014. varying: this._varying
  21015. };
  21016. }
  21017. /**
  21018. * This method is overwritten since the node type from the availability of storage buffers
  21019. * and the attribute data.
  21020. *
  21021. * @param {NodeBuilder} builder - The current node builder.
  21022. * @return {String} The node type.
  21023. */
  21024. getNodeType( builder ) {
  21025. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21026. return super.getNodeType( builder );
  21027. }
  21028. const { attribute } = this.getAttributeData();
  21029. return attribute.getNodeType( builder );
  21030. }
  21031. /**
  21032. * Generates the code snippet of the storage buffer node.
  21033. *
  21034. * @param {NodeBuilder} builder - The current node builder.
  21035. * @return {String} The generated code snippet.
  21036. */
  21037. generate( builder ) {
  21038. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21039. return super.generate( builder );
  21040. }
  21041. const { attribute, varying } = this.getAttributeData();
  21042. const output = varying.build( builder );
  21043. builder.registerTransform( output, attribute );
  21044. return output;
  21045. }
  21046. }
  21047. /**
  21048. * TSL function for creating a storage buffer node.
  21049. *
  21050. * @function
  21051. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21052. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  21053. * @param {Number} [count=0] - The buffer count.
  21054. * @returns {StorageBufferNode}
  21055. */
  21056. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21057. /**
  21058. * @function
  21059. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21060. *
  21061. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21062. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21063. * @param {Number} count - The buffer count.
  21064. * @returns {StorageBufferNode}
  21065. */
  21066. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21067. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21068. return storage( value, type, count ).setPBO( true );
  21069. };
  21070. /** @module Arrays **/
  21071. /**
  21072. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21073. *
  21074. * @function
  21075. * @param {Number} count - The data count.
  21076. * @param {String} [type='float'] - The data type.
  21077. * @returns {StorageBufferNode}
  21078. */
  21079. const attributeArray = ( count, type = 'float' ) => {
  21080. const itemSize = getLengthFromType( type );
  21081. const typedArray = getTypedArrayFromType( type );
  21082. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21083. const node = storage( buffer, type, count );
  21084. return node;
  21085. };
  21086. /**
  21087. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21088. *
  21089. * @function
  21090. * @param {Number} count - The data count.
  21091. * @param {String} [type='float'] - The data type.
  21092. * @returns {StorageBufferNode}
  21093. */
  21094. const instancedArray = ( count, type = 'float' ) => {
  21095. const itemSize = getLengthFromType( type );
  21096. const typedArray = getTypedArrayFromType( type );
  21097. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21098. const node = storage( buffer, type, count );
  21099. return node;
  21100. };
  21101. /** @module VertexColorNode **/
  21102. /**
  21103. * An attribute node for representing vertex colors.
  21104. *
  21105. * @augments module:AttributeNode~AttributeNode
  21106. */
  21107. class VertexColorNode extends AttributeNode {
  21108. static get type() {
  21109. return 'VertexColorNode';
  21110. }
  21111. /**
  21112. * Constructs a new vertex color node.
  21113. *
  21114. * @param {Number} [index=0] - The attribute index.
  21115. */
  21116. constructor( index = 0 ) {
  21117. super( null, 'vec4' );
  21118. /**
  21119. * This flag can be used for type testing.
  21120. *
  21121. * @type {Boolean}
  21122. * @readonly
  21123. * @default true
  21124. */
  21125. this.isVertexColorNode = true;
  21126. /**
  21127. * The attribute index to enable more than one sets of vertex colors.
  21128. *
  21129. * @type {Number}
  21130. * @default 0
  21131. */
  21132. this.index = index;
  21133. }
  21134. /**
  21135. * Overwrites the default implementation by honoring the attribute index.
  21136. *
  21137. * @param {NodeBuilder} builder - The current node builder.
  21138. * @return {String} The attribute name.
  21139. */
  21140. getAttributeName( /*builder*/ ) {
  21141. const index = this.index;
  21142. return 'color' + ( index > 0 ? index : '' );
  21143. }
  21144. generate( builder ) {
  21145. const attributeName = this.getAttributeName( builder );
  21146. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21147. let result;
  21148. if ( geometryAttribute === true ) {
  21149. result = super.generate( builder );
  21150. } else {
  21151. // Vertex color fallback should be white
  21152. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21153. }
  21154. return result;
  21155. }
  21156. serialize( data ) {
  21157. super.serialize( data );
  21158. data.index = this.index;
  21159. }
  21160. deserialize( data ) {
  21161. super.deserialize( data );
  21162. this.index = data.index;
  21163. }
  21164. }
  21165. /**
  21166. * TSL function for creating a reference node.
  21167. *
  21168. * @function
  21169. * @param {Number} index - The attribute index.
  21170. * @returns {VertexColorNode}
  21171. */
  21172. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21173. /** @module PointUVNode **/
  21174. /**
  21175. * A node for representing the uv coordinates of points.
  21176. *
  21177. * Can only be used with a WebGL backend. In WebGPU, point
  21178. * primitives always have the size of one pixel and can thus
  21179. * can't be used as sprite-like objects that display textures.
  21180. *
  21181. * @augments Node
  21182. */
  21183. class PointUVNode extends Node {
  21184. static get type() {
  21185. return 'PointUVNode';
  21186. }
  21187. /**
  21188. * Constructs a new point uv node.
  21189. */
  21190. constructor() {
  21191. super( 'vec2' );
  21192. /**
  21193. * This flag can be used for type testing.
  21194. *
  21195. * @type {Boolean}
  21196. * @readonly
  21197. * @default true
  21198. */
  21199. this.isPointUVNode = true;
  21200. }
  21201. generate( /*builder*/ ) {
  21202. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21203. }
  21204. }
  21205. /**
  21206. * TSL object that represents the uv coordinates of points.
  21207. *
  21208. * @type {PointUVNode}
  21209. */
  21210. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21211. const _e1 = /*@__PURE__*/ new Euler();
  21212. const _m1 = /*@__PURE__*/ new Matrix4();
  21213. /** @module SceneNode **/
  21214. /**
  21215. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21216. * are available for easier use:
  21217. *
  21218. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21219. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21220. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21221. *
  21222. * @augments Node
  21223. */
  21224. class SceneNode extends Node {
  21225. static get type() {
  21226. return 'SceneNode';
  21227. }
  21228. /**
  21229. * Constructs a new scene node.
  21230. *
  21231. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21232. * @param {Scene?} [scene=null] - A reference to the scene.
  21233. */
  21234. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21235. super();
  21236. /**
  21237. * The scope defines the type of scene property that is accessed.
  21238. *
  21239. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21240. */
  21241. this.scope = scope;
  21242. /**
  21243. * A reference to the scene that is going to be accessed.
  21244. *
  21245. * @type {Scene?}
  21246. * @default null
  21247. */
  21248. this.scene = scene;
  21249. }
  21250. /**
  21251. * Depending on the scope, the method returns a different type of node that represents
  21252. * the respective scene property.
  21253. *
  21254. * @param {NodeBuilder} builder - The current node builder.
  21255. * @return {Node} The output node.
  21256. */
  21257. setup( builder ) {
  21258. const scope = this.scope;
  21259. const scene = this.scene !== null ? this.scene : builder.scene;
  21260. let output;
  21261. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21262. output = reference( 'backgroundBlurriness', 'float', scene );
  21263. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21264. output = reference( 'backgroundIntensity', 'float', scene );
  21265. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21266. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21267. const background = scene.background;
  21268. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21269. _e1.copy( scene.backgroundRotation );
  21270. // accommodate left-handed frame
  21271. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  21272. _m1.makeRotationFromEuler( _e1 );
  21273. } else {
  21274. _m1.identity();
  21275. }
  21276. return _m1;
  21277. } );
  21278. } else {
  21279. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21280. }
  21281. return output;
  21282. }
  21283. }
  21284. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21285. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21286. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21287. /**
  21288. * TSL object that represents the scene's background blurriness.
  21289. *
  21290. * @type {SceneNode}
  21291. */
  21292. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21293. /**
  21294. * TSL object that represents the scene's background intensity.
  21295. *
  21296. * @type {SceneNode}
  21297. */
  21298. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21299. /**
  21300. * TSL object that represents the scene's background rotation.
  21301. *
  21302. * @type {SceneNode}
  21303. */
  21304. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21305. /** @module StorageTextureNode **/
  21306. /**
  21307. * This special version of a texture node can be used to
  21308. * write data into a storage texture with a compute shader.
  21309. *
  21310. * ```js
  21311. * const storageTexture = new THREE.StorageTexture( width, height );
  21312. *
  21313. * const computeTexture = Fn( ( { storageTexture } ) => {
  21314. *
  21315. * const posX = instanceIndex.modInt( width );
  21316. * const posY = instanceIndex.div( width );
  21317. * const indexUV = uvec2( posX, posY );
  21318. *
  21319. * // generate RGB values
  21320. *
  21321. * const r = 1;
  21322. * const g = 1;
  21323. * const b = 1;
  21324. *
  21325. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21326. *
  21327. * } );
  21328. *
  21329. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21330. * renderer.computeAsync( computeNode );
  21331. * ```
  21332. *
  21333. * This node can only be used with a WebGPU backend.
  21334. *
  21335. * @augments module:TextureNode~TextureNode
  21336. */
  21337. class StorageTextureNode extends TextureNode {
  21338. static get type() {
  21339. return 'StorageTextureNode';
  21340. }
  21341. /**
  21342. * Constructs a new storage texture node.
  21343. *
  21344. * @param {StorageTexture} value - The storage texture.
  21345. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21346. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21347. */
  21348. constructor( value, uvNode, storeNode = null ) {
  21349. super( value, uvNode );
  21350. /**
  21351. * The value node that should be stored in the texture.
  21352. *
  21353. * @type {Node?}
  21354. * @default null
  21355. */
  21356. this.storeNode = storeNode;
  21357. /**
  21358. * This flag can be used for type testing.
  21359. *
  21360. * @type {Boolean}
  21361. * @readonly
  21362. * @default true
  21363. */
  21364. this.isStorageTextureNode = true;
  21365. /**
  21366. * The access type of the texture node.
  21367. *
  21368. * @type {String}
  21369. * @default 'writeOnly'
  21370. */
  21371. this.access = NodeAccess.WRITE_ONLY;
  21372. }
  21373. /**
  21374. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21375. *
  21376. * @param {NodeBuilder} builder - The current node builder.
  21377. * @return {String} The input type.
  21378. */
  21379. getInputType( /*builder*/ ) {
  21380. return 'storageTexture';
  21381. }
  21382. setup( builder ) {
  21383. super.setup( builder );
  21384. const properties = builder.getNodeProperties( this );
  21385. properties.storeNode = this.storeNode;
  21386. }
  21387. /**
  21388. * Defines the node access.
  21389. *
  21390. * @param {String} value - The node access.
  21391. * @return {StorageTextureNode} A reference to this node.
  21392. */
  21393. setAccess( value ) {
  21394. this.access = value;
  21395. return this;
  21396. }
  21397. /**
  21398. * Generates the code snippet of the stroge node. If no `storeNode`
  21399. * is defined, the texture node is generated as normal texture.
  21400. *
  21401. * @param {NodeBuilder} builder - The current node builder.
  21402. * @param {String} output - The current output.
  21403. * @return {String} The generated code snippet.
  21404. */
  21405. generate( builder, output ) {
  21406. let snippet;
  21407. if ( this.storeNode !== null ) {
  21408. snippet = this.generateStore( builder );
  21409. } else {
  21410. snippet = super.generate( builder, output );
  21411. }
  21412. return snippet;
  21413. }
  21414. /**
  21415. * Convenience method for configuring a read/write node access.
  21416. *
  21417. * @return {StorageTextureNode} A reference to this node.
  21418. */
  21419. toReadWrite() {
  21420. return this.setAccess( NodeAccess.READ_WRITE );
  21421. }
  21422. /**
  21423. * Convenience method for configuring a read-only node access.
  21424. *
  21425. * @return {StorageTextureNode} A reference to this node.
  21426. */
  21427. toReadOnly() {
  21428. return this.setAccess( NodeAccess.READ_ONLY );
  21429. }
  21430. /**
  21431. * Convenience method for configuring a write-only node access.
  21432. *
  21433. * @return {StorageTextureNode} A reference to this node.
  21434. */
  21435. toWriteOnly() {
  21436. return this.setAccess( NodeAccess.WRITE_ONLY );
  21437. }
  21438. /**
  21439. * Generates the code snippet of the storage texture node.
  21440. *
  21441. * @param {NodeBuilder} builder - The current node builder.
  21442. */
  21443. generateStore( builder ) {
  21444. const properties = builder.getNodeProperties( this );
  21445. const { uvNode, storeNode } = properties;
  21446. const textureProperty = super.generate( builder, 'property' );
  21447. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21448. const storeSnippet = storeNode.build( builder, 'vec4' );
  21449. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21450. builder.addLineFlowCode( snippet, this );
  21451. }
  21452. }
  21453. /**
  21454. * TSL function for creating a storage texture node.
  21455. *
  21456. * @function
  21457. * @param {StorageTexture} value - The storage texture.
  21458. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21459. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21460. * @returns {StorageTextureNode}
  21461. */
  21462. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21463. /**
  21464. * TODO: Explain difference to `storageTexture()`.
  21465. *
  21466. * @function
  21467. * @param {StorageTexture} value - The storage texture.
  21468. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21469. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21470. * @returns {StorageTextureNode}
  21471. */
  21472. const textureStore = ( value, uvNode, storeNode ) => {
  21473. const node = storageTexture( value, uvNode, storeNode );
  21474. if ( storeNode !== null ) node.append();
  21475. return node;
  21476. };
  21477. /** @module UserDataNode **/
  21478. /**
  21479. * A special type of reference node that allows to link values in
  21480. * `userData` fields to node objects.
  21481. * ```js
  21482. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21483. *
  21484. * const material = new THREE.SpriteNodeMaterial();
  21485. * material.rotationNode = userData( 'rotation', 'float' );
  21486. * ```
  21487. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21488. * will automatically be updated when the `rotation` user data field changes.
  21489. *
  21490. * @augments module:ReferenceNode~ReferenceNode
  21491. */
  21492. class UserDataNode extends ReferenceNode {
  21493. static get type() {
  21494. return 'UserDataNode';
  21495. }
  21496. /**
  21497. * Constructs a new user data node.
  21498. *
  21499. * @param {String} property - The property name that should be referenced by the node.
  21500. * @param {String} inputType - The node data type of the reference.
  21501. * @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.
  21502. */
  21503. constructor( property, inputType, userData = null ) {
  21504. super( property, inputType, userData );
  21505. /**
  21506. * A reference to the `userData` object. If not provided, the `userData`
  21507. * property of the 3D object that uses the node material is evaluated.
  21508. *
  21509. * @type {Object?}
  21510. * @default null
  21511. */
  21512. this.userData = userData;
  21513. }
  21514. /**
  21515. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21516. * `userData` field.
  21517. *
  21518. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21519. * @return {Object} A reference to the `userData` field.
  21520. */
  21521. updateReference( state ) {
  21522. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21523. return this.reference;
  21524. }
  21525. }
  21526. /**
  21527. * TSL function for creating a user data node.
  21528. *
  21529. * @function
  21530. * @param {String} name - The property name that should be referenced by the node.
  21531. * @param {String} inputType - The node data type of the reference.
  21532. * @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.
  21533. * @returns {UserDataNode}
  21534. */
  21535. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21536. const _objectData = new WeakMap();
  21537. /** @module VelocityNode **/
  21538. /**
  21539. * A node for representing motion or velocity vectors. Foundation
  21540. * for advanced post processing effects like motion blur or TRAA.
  21541. *
  21542. * The node keeps track of the model, view and projection matrices
  21543. * of the previous frame and uses them to compute offsets in NDC space.
  21544. * These offsets represent the final velocity.
  21545. *
  21546. * @augments TempNode
  21547. */
  21548. class VelocityNode extends TempNode {
  21549. static get type() {
  21550. return 'VelocityNode';
  21551. }
  21552. /**
  21553. * Constructs a new vertex color node.
  21554. */
  21555. constructor() {
  21556. super( 'vec2' );
  21557. /**
  21558. * The current projection matrix.
  21559. *
  21560. * @type {Matrix4?}
  21561. * @default null
  21562. */
  21563. this.projectionMatrix = null;
  21564. /**
  21565. * Overwritten since velocity nodes are updated per object.
  21566. *
  21567. * @type {String}
  21568. * @default 'object'
  21569. */
  21570. this.updateType = NodeUpdateType.OBJECT;
  21571. /**
  21572. * Overwritten since velocity nodes save data after the update.
  21573. *
  21574. * @type {String}
  21575. * @default 'object'
  21576. */
  21577. this.updateAfterType = NodeUpdateType.OBJECT;
  21578. /**
  21579. * Uniform node representing the previous model matrix in world space.
  21580. *
  21581. * @type {UniformNode<mat4>}
  21582. * @default null
  21583. */
  21584. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21585. /**
  21586. * Uniform node representing the previous projection matrix.
  21587. *
  21588. * @type {UniformNode<mat4>}
  21589. * @default null
  21590. */
  21591. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21592. /**
  21593. * Uniform node representing the previous view matrix.
  21594. *
  21595. * @type {UniformNode<mat4>}
  21596. * @default null
  21597. */
  21598. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21599. }
  21600. /**
  21601. * Sets the given projection matrix.
  21602. *
  21603. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21604. */
  21605. setProjectionMatrix( projectionMatrix ) {
  21606. this.projectionMatrix = projectionMatrix;
  21607. }
  21608. /**
  21609. * Updates velocity specific uniforms.
  21610. *
  21611. * @param {NodeFrame} frame - A reference to the current node frame.
  21612. */
  21613. update( { frameId, camera, object } ) {
  21614. const previousModelMatrix = getPreviousMatrix( object );
  21615. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21616. //
  21617. const cameraData = getData( camera );
  21618. if ( cameraData.frameId !== frameId ) {
  21619. cameraData.frameId = frameId;
  21620. if ( cameraData.previousProjectionMatrix === undefined ) {
  21621. cameraData.previousProjectionMatrix = new Matrix4();
  21622. cameraData.previousCameraViewMatrix = new Matrix4();
  21623. cameraData.currentProjectionMatrix = new Matrix4();
  21624. cameraData.currentCameraViewMatrix = new Matrix4();
  21625. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21626. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21627. } else {
  21628. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21629. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21630. }
  21631. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21632. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21633. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21634. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21635. }
  21636. }
  21637. /**
  21638. * Overwritten to updated velocity specific uniforms.
  21639. *
  21640. * @param {NodeFrame} frame - A reference to the current node frame.
  21641. */
  21642. updateAfter( { object } ) {
  21643. getPreviousMatrix( object ).copy( object.matrixWorld );
  21644. }
  21645. /**
  21646. * Implements the velocity computation based on the previous and current vertex data.
  21647. *
  21648. * @param {NodeBuilder} builder - A reference to the current node builder.
  21649. * @return {Node<vec2>} The motion vector.
  21650. */
  21651. setup( /*builder*/ ) {
  21652. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21653. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21654. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21655. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21656. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21657. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21658. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21659. return velocity;
  21660. }
  21661. }
  21662. function getData( object ) {
  21663. let objectData = _objectData.get( object );
  21664. if ( objectData === undefined ) {
  21665. objectData = {};
  21666. _objectData.set( object, objectData );
  21667. }
  21668. return objectData;
  21669. }
  21670. function getPreviousMatrix( object, index = 0 ) {
  21671. const objectData = getData( object );
  21672. let matrix = objectData[ index ];
  21673. if ( matrix === undefined ) {
  21674. objectData[ index ] = matrix = new Matrix4();
  21675. }
  21676. return matrix;
  21677. }
  21678. /**
  21679. * TSL object that represents the velocity of a render pass.
  21680. *
  21681. * @type {VelocityNode}
  21682. */
  21683. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21684. /** @module BlendModes **/
  21685. /**
  21686. * Represents a "Color Burn" blend mode.
  21687. *
  21688. * It's designed to darken the base layer's colors based on the color of the blend layer.
  21689. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  21690. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  21691. *
  21692. * @method
  21693. * @param {Node<vec3>} base - The base color.
  21694. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  21695. * @return {Node<vec3>} The result.
  21696. */
  21697. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21698. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21699. } ).setLayout( {
  21700. name: 'blendBurn',
  21701. type: 'vec3',
  21702. inputs: [
  21703. { name: 'base', type: 'vec3' },
  21704. { name: 'blend', type: 'vec3' }
  21705. ]
  21706. } );
  21707. /**
  21708. * Represents a "Color Dodge" blend mode.
  21709. *
  21710. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  21711. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  21712. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  21713. *
  21714. * @method
  21715. * @param {Node<vec3>} base - The base color.
  21716. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21717. * @return {Node<vec3>} The result.
  21718. */
  21719. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21720. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21721. } ).setLayout( {
  21722. name: 'blendDodge',
  21723. type: 'vec3',
  21724. inputs: [
  21725. { name: 'base', type: 'vec3' },
  21726. { name: 'blend', type: 'vec3' }
  21727. ]
  21728. } );
  21729. /**
  21730. * Represents a "Screen" blend mode.
  21731. *
  21732. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  21733. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  21734. * effects.
  21735. *
  21736. * @method
  21737. * @param {Node<vec3>} base - The base color.
  21738. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21739. * @return {Node<vec3>} The result.
  21740. */
  21741. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21742. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21743. } ).setLayout( {
  21744. name: 'blendScreen',
  21745. type: 'vec3',
  21746. inputs: [
  21747. { name: 'base', type: 'vec3' },
  21748. { name: 'blend', type: 'vec3' }
  21749. ]
  21750. } );
  21751. /**
  21752. * Represents a "Overlay" blend mode.
  21753. *
  21754. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  21755. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  21756. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  21757. *
  21758. * @method
  21759. * @param {Node<vec3>} base - The base color.
  21760. * @param {Node<vec3>} blend - The blend color
  21761. * @return {Node<vec3>} The result.
  21762. */
  21763. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21764. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21765. } ).setLayout( {
  21766. name: 'blendOverlay',
  21767. type: 'vec3',
  21768. inputs: [
  21769. { name: 'base', type: 'vec3' },
  21770. { name: 'blend', type: 'vec3' }
  21771. ]
  21772. } );
  21773. /**
  21774. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  21775. * It assumes both input colors have non-preumiltiplied alpha.
  21776. *
  21777. * @method
  21778. * @param {Node<vec4>} base - The base color.
  21779. * @param {Node<vec4>} blend - The blend color
  21780. * @return {Node<vec4>} The result.
  21781. */
  21782. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21783. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21784. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21785. } ).setLayout( {
  21786. name: 'blendColor',
  21787. type: 'vec4',
  21788. inputs: [
  21789. { name: 'base', type: 'vec4' },
  21790. { name: 'blend', type: 'vec4' }
  21791. ]
  21792. } );
  21793. // Deprecated
  21794. /**
  21795. * @function
  21796. * @deprecated since r171. Use {@link blendBurn} instead.
  21797. *
  21798. * @param {...any} params
  21799. * @returns {Function}
  21800. */
  21801. const burn = ( ...params ) => { // @deprecated, r171
  21802. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21803. return blendBurn( params );
  21804. };
  21805. /**
  21806. * @function
  21807. * @deprecated since r171. Use {@link blendDodge} instead.
  21808. *
  21809. * @param {...any} params
  21810. * @returns {Function}
  21811. */
  21812. const dodge = ( ...params ) => { // @deprecated, r171
  21813. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21814. return blendDodge( params );
  21815. };
  21816. /**
  21817. * @method
  21818. * @deprecated since r171. Use {@link blendScreen} instead.
  21819. *
  21820. * @param {...any} params
  21821. * @returns {Function}
  21822. */
  21823. const screen = ( ...params ) => { // @deprecated, r171
  21824. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21825. return blendScreen( params );
  21826. };
  21827. /**
  21828. * @method
  21829. * @deprecated since r171. Use {@link blendOverlay} instead.
  21830. *
  21831. * @param {...any} params
  21832. * @returns {Function}
  21833. */
  21834. const overlay = ( ...params ) => { // @deprecated, r171
  21835. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21836. return blendOverlay( params );
  21837. };
  21838. /** @module ColorAdjustment **/
  21839. /**
  21840. * Computes a grayscale value for the given RGB color value.
  21841. *
  21842. * @method
  21843. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21844. * @return {Node<vec3>} The grayscale color.
  21845. */
  21846. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21847. return luminance( color.rgb );
  21848. } );
  21849. /**
  21850. * Super-saturates or desaturates the given RGB color.
  21851. *
  21852. * @method
  21853. * @param {Node<vec3>} color - The input color.
  21854. * @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.
  21855. * @return {Node<vec3>} The saturated color.
  21856. */
  21857. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21858. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21859. } );
  21860. /**
  21861. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21862. * in a more natural and visually appealing image with enhanced color depth
  21863. * compared to {@link ColorAdjustment#saturation}.
  21864. *
  21865. * @method
  21866. * @param {Node<vec3>} color - The input color.
  21867. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21868. * @return {Node<vec3>} The updated color.
  21869. */
  21870. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21871. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21872. const mx = color.r.max( color.g.max( color.b ) );
  21873. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  21874. return mix( color.rgb, mx, amt );
  21875. } );
  21876. /**
  21877. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21878. *
  21879. * @method
  21880. * @param {Node<vec3>} color - The input color.
  21881. * @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.
  21882. * @return {Node<vec3>} The updated color.
  21883. */
  21884. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21885. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21886. const cosAngle = adjustment.cos();
  21887. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21888. } );
  21889. /**
  21890. * Computes the luminance for the given RGB color value.
  21891. *
  21892. * @method
  21893. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21894. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21895. * @return {Node<vec3>} The luminance.
  21896. */
  21897. const luminance = (
  21898. color,
  21899. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21900. ) => dot( color, luminanceCoefficients );
  21901. /**
  21902. * Color Decision List (CDL) v1.2
  21903. *
  21904. * Compact representation of color grading information, defined by slope, offset, power, and
  21905. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21906. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21907. *
  21908. * @method
  21909. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21910. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21911. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21912. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21913. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21914. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21915. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21916. *
  21917. * References:
  21918. * - ASC CDL v1.2
  21919. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21920. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21921. */
  21922. const cdl = /*@__PURE__*/ Fn( ( [
  21923. color,
  21924. slope = vec3( 1 ),
  21925. offset = vec3( 0 ),
  21926. power = vec3( 1 ),
  21927. saturation = float( 1 ),
  21928. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21929. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21930. ] ) => {
  21931. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21932. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21933. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21934. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21935. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21936. const pv = v.pow( power ).toVar();
  21937. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21938. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21939. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21940. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21941. return vec4( v.rgb, color.a );
  21942. } );
  21943. /** @module PosterizeNode **/
  21944. /**
  21945. * Represents a posterize effect which reduces the number of colors
  21946. * in an image, resulting in a more blocky and stylized appearance.
  21947. *
  21948. * @augments TempNode
  21949. */
  21950. class PosterizeNode extends TempNode {
  21951. static get type() {
  21952. return 'PosterizeNode';
  21953. }
  21954. /**
  21955. * Constructs a new posterize node.
  21956. *
  21957. * @param {Node} sourceNode - The input color.
  21958. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21959. */
  21960. constructor( sourceNode, stepsNode ) {
  21961. super();
  21962. /**
  21963. * The input color.
  21964. *
  21965. * @type {Node}
  21966. */
  21967. this.sourceNode = sourceNode;
  21968. /**
  21969. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21970. *
  21971. * @type {Node}
  21972. */
  21973. this.stepsNode = stepsNode;
  21974. }
  21975. setup() {
  21976. const { sourceNode, stepsNode } = this;
  21977. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21978. }
  21979. }
  21980. /**
  21981. * TSL function for creating a posterize node.
  21982. *
  21983. * @function
  21984. * @param {Node} sourceNode - The input color.
  21985. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21986. * @returns {PosterizeNode}
  21987. */
  21988. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21989. /** @module PassNode **/
  21990. const _size = /*@__PURE__*/ new Vector2();
  21991. /**
  21992. * Represents the texture of a pass node.
  21993. *
  21994. * @augments module:TextureNode~TextureNode
  21995. */
  21996. class PassTextureNode extends TextureNode {
  21997. static get type() {
  21998. return 'PassTextureNode';
  21999. }
  22000. /**
  22001. * Constructs a new pass texture node.
  22002. *
  22003. * @param {PassNode} passNode - The pass node.
  22004. * @param {Texture} texture - The output texture.
  22005. */
  22006. constructor( passNode, texture ) {
  22007. super( texture );
  22008. /**
  22009. * A reference to the pass node.
  22010. *
  22011. * @type {PassNode}
  22012. */
  22013. this.passNode = passNode;
  22014. this.setUpdateMatrix( false );
  22015. }
  22016. setup( builder ) {
  22017. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22018. return super.setup( builder );
  22019. }
  22020. clone() {
  22021. return new this.constructor( this.passNode, this.value );
  22022. }
  22023. }
  22024. /**
  22025. * An extension of `PassTextureNode` which allows to manage more than one
  22026. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22027. *
  22028. * @augments module:PassTextureNode~PassTextureNode
  22029. */
  22030. class PassMultipleTextureNode extends PassTextureNode {
  22031. static get type() {
  22032. return 'PassMultipleTextureNode';
  22033. }
  22034. /**
  22035. * Constructs a new pass texture node.
  22036. *
  22037. * @param {PassNode} passNode - The pass node.
  22038. * @param {String} textureName - The output texture name.
  22039. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22040. */
  22041. constructor( passNode, textureName, previousTexture = false ) {
  22042. // null is passed to the super call since this class does not
  22043. // use an external texture for rendering pass data into. Instead
  22044. // the texture is managed by the pass node itself
  22045. super( passNode, null );
  22046. /**
  22047. * The output texture name.
  22048. *
  22049. * @type {String}
  22050. */
  22051. this.textureName = textureName;
  22052. /**
  22053. * Whether previous frame data should be used or not.
  22054. *
  22055. * @type {Boolean}
  22056. */
  22057. this.previousTexture = previousTexture;
  22058. }
  22059. /**
  22060. * Updates the texture reference of this node.
  22061. */
  22062. updateTexture() {
  22063. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22064. }
  22065. setup( builder ) {
  22066. this.updateTexture();
  22067. return super.setup( builder );
  22068. }
  22069. clone() {
  22070. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22071. }
  22072. }
  22073. /**
  22074. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22075. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22076. * via MRT for further processing.
  22077. *
  22078. * ```js
  22079. * const postProcessing = new PostProcessing( renderer );
  22080. *
  22081. * const scenePass = pass( scene, camera );
  22082. *
  22083. * postProcessing.outputNode = scenePass;
  22084. * ```
  22085. *
  22086. * @augments TempNode
  22087. */
  22088. class PassNode extends TempNode {
  22089. static get type() {
  22090. return 'PassNode';
  22091. }
  22092. /**
  22093. * Constructs a new pass node.
  22094. *
  22095. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22096. * @param {Scene} scene - A reference to the scene.
  22097. * @param {Camera} camera - A reference to the camera.
  22098. * @param {Object} options - Options for the internal render target.
  22099. */
  22100. constructor( scope, scene, camera, options = {} ) {
  22101. super( 'vec4' );
  22102. /**
  22103. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22104. *
  22105. * @type {('color'|'depth')}
  22106. */
  22107. this.scope = scope;
  22108. /**
  22109. * A reference to the scene.
  22110. *
  22111. * @type {Scene}
  22112. */
  22113. this.scene = scene;
  22114. /**
  22115. * A reference to the camera.
  22116. *
  22117. * @type {Camera}
  22118. */
  22119. this.camera = camera;
  22120. /**
  22121. * Options for the internal render target.
  22122. *
  22123. * @type {Object}
  22124. */
  22125. this.options = options;
  22126. /**
  22127. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22128. *
  22129. * @private
  22130. * @type {Number}
  22131. * @default 1
  22132. */
  22133. this._pixelRatio = 1;
  22134. /**
  22135. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22136. * @private
  22137. * @type {Number}
  22138. * @default 1
  22139. */
  22140. this._width = 1;
  22141. /**
  22142. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22143. * @private
  22144. * @type {Number}
  22145. * @default 1
  22146. */
  22147. this._height = 1;
  22148. const depthTexture = new DepthTexture();
  22149. depthTexture.isRenderTargetTexture = true;
  22150. //depthTexture.type = FloatType;
  22151. depthTexture.name = 'depth';
  22152. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22153. renderTarget.texture.name = 'output';
  22154. renderTarget.depthTexture = depthTexture;
  22155. /**
  22156. * The pass's render target.
  22157. *
  22158. * @type {RenderTarget}
  22159. */
  22160. this.renderTarget = renderTarget;
  22161. /**
  22162. * A dictionary holding the internal result textures.
  22163. *
  22164. * @private
  22165. * @type {Object<String, Texture>}
  22166. */
  22167. this._textures = {
  22168. output: renderTarget.texture,
  22169. depth: depthTexture
  22170. };
  22171. /**
  22172. * A dictionary holding the internal texture nodes.
  22173. *
  22174. * @private
  22175. * @type {Object<String, TextureNode>}
  22176. */
  22177. this._textureNodes = {};
  22178. /**
  22179. * A dictionary holding the internal depth nodes.
  22180. *
  22181. * @private
  22182. * @type {Object}
  22183. */
  22184. this._linearDepthNodes = {};
  22185. /**
  22186. * A dictionary holding the internal viewZ nodes.
  22187. *
  22188. * @private
  22189. * @type {Object}
  22190. */
  22191. this._viewZNodes = {};
  22192. /**
  22193. * A dictionary holding the texture data of the previous frame.
  22194. * Used for computing velocity/motion vectors.
  22195. *
  22196. * @private
  22197. * @type {Object<String, Texture>}
  22198. */
  22199. this._previousTextures = {};
  22200. /**
  22201. * A dictionary holding the texture nodes of the previous frame.
  22202. * Used for computing velocity/motion vectors.
  22203. *
  22204. * @private
  22205. * @type {Object<String, TextureNode>}
  22206. */
  22207. this._previousTextureNodes = {};
  22208. /**
  22209. * The `near` property of the camera as a uniform.
  22210. *
  22211. * @private
  22212. * @type {UniformNode}
  22213. */
  22214. this._cameraNear = uniform( 0 );
  22215. /**
  22216. * The `far` property of the camera as a uniform.
  22217. *
  22218. * @private
  22219. * @type {UniformNode}
  22220. */
  22221. this._cameraFar = uniform( 0 );
  22222. /**
  22223. * A MRT node configuring the MRT settings.
  22224. *
  22225. * @private
  22226. * @type {MRTNode?}
  22227. * @default null
  22228. */
  22229. this._mrt = null;
  22230. /**
  22231. * This flag can be used for type testing.
  22232. *
  22233. * @type {Boolean}
  22234. * @readonly
  22235. * @default true
  22236. */
  22237. this.isPassNode = true;
  22238. /**
  22239. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22240. * scene once per frame in its {@link PassNode#updateBefore} method.
  22241. *
  22242. * @type {String}
  22243. * @default 'frame'
  22244. */
  22245. this.updateBeforeType = NodeUpdateType.FRAME;
  22246. }
  22247. /**
  22248. * Sets the given MRT node to setup MRT for this pass.
  22249. *
  22250. * @param {MRTNode} mrt - The MRT object.
  22251. * @return {PassNode} A reference to this pass.
  22252. */
  22253. setMRT( mrt ) {
  22254. this._mrt = mrt;
  22255. return this;
  22256. }
  22257. /**
  22258. * Returns the current MRT node.
  22259. *
  22260. * @return {MRTNode} The current MRT node.
  22261. */
  22262. getMRT() {
  22263. return this._mrt;
  22264. }
  22265. /**
  22266. * The method is overwritten so it always returns `true`.
  22267. *
  22268. * @return {Boolean} Whether this node is global or not.
  22269. */
  22270. isGlobal() {
  22271. return true;
  22272. }
  22273. /**
  22274. * Returns the texture for the given output name.
  22275. *
  22276. * @param {String} name - The output name to get the texture for.
  22277. * @return {Texture} The texture.
  22278. */
  22279. getTexture( name ) {
  22280. let texture = this._textures[ name ];
  22281. if ( texture === undefined ) {
  22282. const refTexture = this.renderTarget.texture;
  22283. texture = refTexture.clone();
  22284. texture.name = name;
  22285. this._textures[ name ] = texture;
  22286. this.renderTarget.textures.push( texture );
  22287. }
  22288. return texture;
  22289. }
  22290. /**
  22291. * Returns the texture holding the data of the previous frame for the given output name.
  22292. *
  22293. * @param {String} name - The output name to get the texture for.
  22294. * @return {Texture} The texture holding the data of the previous frame.
  22295. */
  22296. getPreviousTexture( name ) {
  22297. let texture = this._previousTextures[ name ];
  22298. if ( texture === undefined ) {
  22299. texture = this.getTexture( name ).clone();
  22300. this._previousTextures[ name ] = texture;
  22301. }
  22302. return texture;
  22303. }
  22304. /**
  22305. * Switches current and previous textures for the given output name.
  22306. *
  22307. * @param {String} name - The output name.
  22308. */
  22309. toggleTexture( name ) {
  22310. const prevTexture = this._previousTextures[ name ];
  22311. if ( prevTexture !== undefined ) {
  22312. const texture = this._textures[ name ];
  22313. const index = this.renderTarget.textures.indexOf( texture );
  22314. this.renderTarget.textures[ index ] = prevTexture;
  22315. this._textures[ name ] = prevTexture;
  22316. this._previousTextures[ name ] = texture;
  22317. this._textureNodes[ name ].updateTexture();
  22318. this._previousTextureNodes[ name ].updateTexture();
  22319. }
  22320. }
  22321. /**
  22322. * Returns the texture node for the given output name.
  22323. *
  22324. * @param {String} [name='output'] - The output name to get the texture node for.
  22325. * @return {TextureNode} The texture node.
  22326. */
  22327. getTextureNode( name = 'output' ) {
  22328. let textureNode = this._textureNodes[ name ];
  22329. if ( textureNode === undefined ) {
  22330. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22331. textureNode.updateTexture();
  22332. this._textureNodes[ name ] = textureNode;
  22333. }
  22334. return textureNode;
  22335. }
  22336. /**
  22337. * Returns the previous texture node for the given output name.
  22338. *
  22339. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22340. * @return {TextureNode} The previous texture node.
  22341. */
  22342. getPreviousTextureNode( name = 'output' ) {
  22343. let textureNode = this._previousTextureNodes[ name ];
  22344. if ( textureNode === undefined ) {
  22345. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22346. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22347. textureNode.updateTexture();
  22348. this._previousTextureNodes[ name ] = textureNode;
  22349. }
  22350. return textureNode;
  22351. }
  22352. /**
  22353. * Returns a viewZ node of this pass.
  22354. *
  22355. * @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.
  22356. * @return {Node} The viewZ node.
  22357. */
  22358. getViewZNode( name = 'depth' ) {
  22359. let viewZNode = this._viewZNodes[ name ];
  22360. if ( viewZNode === undefined ) {
  22361. const cameraNear = this._cameraNear;
  22362. const cameraFar = this._cameraFar;
  22363. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22364. }
  22365. return viewZNode;
  22366. }
  22367. /**
  22368. * Returns a linear depth node of this pass.
  22369. *
  22370. * @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.
  22371. * @return {Node} The linear depth node.
  22372. */
  22373. getLinearDepthNode( name = 'depth' ) {
  22374. let linearDepthNode = this._linearDepthNodes[ name ];
  22375. if ( linearDepthNode === undefined ) {
  22376. const cameraNear = this._cameraNear;
  22377. const cameraFar = this._cameraFar;
  22378. const viewZNode = this.getViewZNode( name );
  22379. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22380. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22381. }
  22382. return linearDepthNode;
  22383. }
  22384. setup( { renderer } ) {
  22385. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22386. // Disable MSAA for WebGL backend for now
  22387. if ( renderer.backend.isWebGLBackend === true ) {
  22388. this.renderTarget.samples = 0;
  22389. }
  22390. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22391. }
  22392. updateBefore( frame ) {
  22393. const { renderer } = frame;
  22394. const { scene, camera } = this;
  22395. this._pixelRatio = renderer.getPixelRatio();
  22396. const size = renderer.getSize( _size );
  22397. this.setSize( size.width, size.height );
  22398. const currentRenderTarget = renderer.getRenderTarget();
  22399. const currentMRT = renderer.getMRT();
  22400. this._cameraNear.value = camera.near;
  22401. this._cameraFar.value = camera.far;
  22402. for ( const name in this._previousTextures ) {
  22403. this.toggleTexture( name );
  22404. }
  22405. renderer.setRenderTarget( this.renderTarget );
  22406. renderer.setMRT( this._mrt );
  22407. renderer.render( scene, camera );
  22408. renderer.setRenderTarget( currentRenderTarget );
  22409. renderer.setMRT( currentMRT );
  22410. }
  22411. /**
  22412. * Sets the size of the pass's render target. Honors the pixel ratio.
  22413. *
  22414. * @param {Number} width - The width to set.
  22415. * @param {Number} height - The height to set.
  22416. */
  22417. setSize( width, height ) {
  22418. this._width = width;
  22419. this._height = height;
  22420. const effectiveWidth = this._width * this._pixelRatio;
  22421. const effectiveHeight = this._height * this._pixelRatio;
  22422. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22423. }
  22424. /**
  22425. * Sets the pixel ratio the pass's render target and updates the size.
  22426. *
  22427. * @param {Number} pixelRatio - The pixel ratio to set.
  22428. */
  22429. setPixelRatio( pixelRatio ) {
  22430. this._pixelRatio = pixelRatio;
  22431. this.setSize( this._width, this._height );
  22432. }
  22433. /**
  22434. * Frees internal resources. Should be called when the node is no longer in use.
  22435. */
  22436. dispose() {
  22437. this.renderTarget.dispose();
  22438. }
  22439. }
  22440. PassNode.COLOR = 'color';
  22441. PassNode.DEPTH = 'depth';
  22442. /**
  22443. * TSL function for creating a pass node.
  22444. *
  22445. * @function
  22446. * @param {Scene} scene - A reference to the scene.
  22447. * @param {Camera} camera - A reference to the camera.
  22448. * @param {Object} options - Options for the internal render target.
  22449. * @returns {PassNode}
  22450. */
  22451. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22452. /**
  22453. * TSL function for creating a pass texture node.
  22454. *
  22455. * @function
  22456. * @param {PassNode} pass - The pass node.
  22457. * @param {Texture} texture - The output texture.
  22458. * @returns {PassTextureNode}
  22459. */
  22460. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22461. /**
  22462. * TSL function for creating a depth pass node.
  22463. *
  22464. * @function
  22465. * @param {Scene} scene - A reference to the scene.
  22466. * @param {Camera} camera - A reference to the camera.
  22467. * @param {Object} options - Options for the internal render target.
  22468. * @returns {PassNode}
  22469. */
  22470. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22471. /** @module ToonOutlinePassNode **/
  22472. /**
  22473. * Represents a render pass for producing a toon outline effect on compatible objects.
  22474. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22475. * will receive the outline.
  22476. *
  22477. * ```js
  22478. * const postProcessing = new PostProcessing( renderer );
  22479. *
  22480. * const scenePass = toonOutlinePass( scene, camera );
  22481. *
  22482. * postProcessing.outputNode = scenePass;
  22483. * ```
  22484. * @augments PassNode
  22485. */
  22486. class ToonOutlinePassNode extends PassNode {
  22487. static get type() {
  22488. return 'ToonOutlinePassNode';
  22489. }
  22490. /**
  22491. * Constructs a new outline pass node.
  22492. *
  22493. * @param {Scene} scene - A reference to the scene.
  22494. * @param {Camera} camera - A reference to the camera.
  22495. * @param {Node} colorNode - Defines the outline's color.
  22496. * @param {Node} thicknessNode - Defines the outline's thickness.
  22497. * @param {Node} alphaNode - Defines the outline's alpha.
  22498. */
  22499. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22500. super( PassNode.COLOR, scene, camera );
  22501. /**
  22502. * Defines the outline's color.
  22503. *
  22504. * @type {Node}
  22505. */
  22506. this.colorNode = colorNode;
  22507. /**
  22508. * Defines the outline's thickness.
  22509. *
  22510. * @type {Node}
  22511. */
  22512. this.thicknessNode = thicknessNode;
  22513. /**
  22514. * Defines the outline's alpha.
  22515. *
  22516. * @type {Node}
  22517. */
  22518. this.alphaNode = alphaNode;
  22519. /**
  22520. * An internal material cache.
  22521. *
  22522. * @private
  22523. * @type {WeakMap<Material, NodeMaterial>}
  22524. */
  22525. this._materialCache = new WeakMap();
  22526. }
  22527. updateBefore( frame ) {
  22528. const { renderer } = frame;
  22529. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22530. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22531. // only render outline for supported materials
  22532. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22533. if ( material.wireframe === false ) {
  22534. const outlineMaterial = this._getOutlineMaterial( material );
  22535. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22536. }
  22537. }
  22538. // default
  22539. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22540. } );
  22541. super.updateBefore( frame );
  22542. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22543. }
  22544. /**
  22545. * Creates the material used for outline rendering.
  22546. *
  22547. * @private
  22548. * @return {NodeMaterial} The outline material.
  22549. */
  22550. _createMaterial() {
  22551. const material = new NodeMaterial();
  22552. material.isMeshToonOutlineMaterial = true;
  22553. material.name = 'Toon_Outline';
  22554. material.side = BackSide;
  22555. // vertex node
  22556. const outlineNormal = normalLocal.negate();
  22557. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22558. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22559. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22560. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22561. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22562. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22563. // color node
  22564. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22565. return material;
  22566. }
  22567. /**
  22568. * For the given toon material, this method returns a corresponding
  22569. * outline material.
  22570. *
  22571. * @private
  22572. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22573. * @return {NodeMaterial} The outline material.
  22574. */
  22575. _getOutlineMaterial( originalMaterial ) {
  22576. let outlineMaterial = this._materialCache.get( originalMaterial );
  22577. if ( outlineMaterial === undefined ) {
  22578. outlineMaterial = this._createMaterial();
  22579. this._materialCache.set( originalMaterial, outlineMaterial );
  22580. }
  22581. return outlineMaterial;
  22582. }
  22583. }
  22584. /**
  22585. * TSL function for creating a toon outline pass node.
  22586. *
  22587. * @function
  22588. * @param {Scene} scene - A reference to the scene.
  22589. * @param {Camera} camera - A reference to the camera.
  22590. * @param {Color} color - Defines the outline's color.
  22591. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22592. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22593. * @returns {ToonOutlinePassNode}
  22594. */
  22595. 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 ) ) );
  22596. /** @module ToneMappingFunctions **/
  22597. /**
  22598. * Linear tone mapping, exposure only.
  22599. *
  22600. * @method
  22601. * @param {Node<vec3>} color - The color that should be tone mapped.
  22602. * @param {Node<float>} exposure - The exposure.
  22603. * @return {Node<vec3>} The tone mapped color.
  22604. */
  22605. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22606. return color.mul( exposure ).clamp();
  22607. } ).setLayout( {
  22608. name: 'linearToneMapping',
  22609. type: 'vec3',
  22610. inputs: [
  22611. { name: 'color', type: 'vec3' },
  22612. { name: 'exposure', type: 'float' }
  22613. ]
  22614. } );
  22615. /**
  22616. * Reinhard tone mapping.
  22617. *
  22618. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22619. *
  22620. * @method
  22621. * @param {Node<vec3>} color - The color that should be tone mapped.
  22622. * @param {Node<float>} exposure - The exposure.
  22623. * @return {Node<vec3>} The tone mapped color.
  22624. */
  22625. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22626. color = color.mul( exposure );
  22627. return color.div( color.add( 1.0 ) ).clamp();
  22628. } ).setLayout( {
  22629. name: 'reinhardToneMapping',
  22630. type: 'vec3',
  22631. inputs: [
  22632. { name: 'color', type: 'vec3' },
  22633. { name: 'exposure', type: 'float' }
  22634. ]
  22635. } );
  22636. /**
  22637. * Cineon tone mapping.
  22638. *
  22639. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22640. *
  22641. * @method
  22642. * @param {Node<vec3>} color - The color that should be tone mapped.
  22643. * @param {Node<float>} exposure - The exposure.
  22644. * @return {Node<vec3>} The tone mapped color.
  22645. */
  22646. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22647. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22648. color = color.mul( exposure );
  22649. color = color.sub( 0.004 ).max( 0.0 );
  22650. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22651. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22652. return a.div( b ).pow( 2.2 );
  22653. } ).setLayout( {
  22654. name: 'cineonToneMapping',
  22655. type: 'vec3',
  22656. inputs: [
  22657. { name: 'color', type: 'vec3' },
  22658. { name: 'exposure', type: 'float' }
  22659. ]
  22660. } );
  22661. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22662. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22663. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22664. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22665. return a.div( b );
  22666. } );
  22667. /**
  22668. * ACESFilmic tone mapping.
  22669. *
  22670. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22671. *
  22672. * @method
  22673. * @param {Node<vec3>} color - The color that should be tone mapped.
  22674. * @param {Node<float>} exposure - The exposure.
  22675. * @return {Node<vec3>} The tone mapped color.
  22676. */
  22677. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22678. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22679. const ACESInputMat = mat3(
  22680. 0.59719, 0.35458, 0.04823,
  22681. 0.07600, 0.90834, 0.01566,
  22682. 0.02840, 0.13383, 0.83777
  22683. );
  22684. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22685. const ACESOutputMat = mat3(
  22686. 1.60475, -0.53108, -0.07367,
  22687. -0.10208, 1.10813, -605e-5,
  22688. -327e-5, -0.07276, 1.07602
  22689. );
  22690. color = color.mul( exposure ).div( 0.6 );
  22691. color = ACESInputMat.mul( color );
  22692. // Apply RRT and ODT
  22693. color = RRTAndODTFit( color );
  22694. color = ACESOutputMat.mul( color );
  22695. // Clamp to [0, 1]
  22696. return color.clamp();
  22697. } ).setLayout( {
  22698. name: 'acesFilmicToneMapping',
  22699. type: 'vec3',
  22700. inputs: [
  22701. { name: 'color', type: 'vec3' },
  22702. { name: 'exposure', type: 'float' }
  22703. ]
  22704. } );
  22705. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, -0.1246, -0.0182 ), vec3( -0.5876, 1.1329, -0.1006 ), vec3( -0.0728, -83e-4, 1.1187 ) );
  22706. 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 ) );
  22707. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22708. const x = vec3( x_immutable ).toVar();
  22709. const x2 = vec3( x.mul( x ) ).toVar();
  22710. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22711. 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 ) ) ) );
  22712. } );
  22713. /**
  22714. * AgX tone mapping.
  22715. *
  22716. * @method
  22717. * @param {Node<vec3>} color - The color that should be tone mapped.
  22718. * @param {Node<float>} exposure - The exposure.
  22719. * @return {Node<vec3>} The tone mapped color.
  22720. */
  22721. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22722. const colortone = vec3( color ).toVar();
  22723. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22724. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  22725. const AgxMinEv = float( -12.47393 );
  22726. const AgxMaxEv = float( 4.026069 );
  22727. colortone.mulAssign( exposure );
  22728. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22729. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22730. colortone.assign( max$1( colortone, 1e-10 ) );
  22731. colortone.assign( log2( colortone ) );
  22732. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22733. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22734. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22735. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22736. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22737. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22738. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22739. return colortone;
  22740. } ).setLayout( {
  22741. name: 'agxToneMapping',
  22742. type: 'vec3',
  22743. inputs: [
  22744. { name: 'color', type: 'vec3' },
  22745. { name: 'exposure', type: 'float' }
  22746. ]
  22747. } );
  22748. /**
  22749. * Neutral tone mapping.
  22750. *
  22751. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22752. *
  22753. * @method
  22754. * @param {Node<vec3>} color - The color that should be tone mapped.
  22755. * @param {Node<float>} exposure - The exposure.
  22756. * @return {Node<vec3>} The tone mapped color.
  22757. */
  22758. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22759. const StartCompression = float( 0.8 - 0.04 );
  22760. const Desaturation = float( 0.15 );
  22761. color = color.mul( exposure );
  22762. const x = min$1( color.r, min$1( color.g, color.b ) );
  22763. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22764. color.subAssign( offset );
  22765. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22766. If( peak.lessThan( StartCompression ), () => {
  22767. return color;
  22768. } );
  22769. const d = sub( 1, StartCompression );
  22770. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22771. color.mulAssign( newPeak.div( peak ) );
  22772. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22773. return mix( color, vec3( newPeak ), g );
  22774. } ).setLayout( {
  22775. name: 'neutralToneMapping',
  22776. type: 'vec3',
  22777. inputs: [
  22778. { name: 'color', type: 'vec3' },
  22779. { name: 'exposure', type: 'float' }
  22780. ]
  22781. } );
  22782. /** @module CodeNode **/
  22783. /**
  22784. * This class represents native code sections. It is the base
  22785. * class for modules like {@link FunctionNode} which allows to implement
  22786. * functions with native shader languages.
  22787. *
  22788. * @augments Node
  22789. */
  22790. class CodeNode extends Node {
  22791. static get type() {
  22792. return 'CodeNode';
  22793. }
  22794. /**
  22795. * Constructs a new code node.
  22796. *
  22797. * @param {String} [code=''] - The native code.
  22798. * @param {Array<Node>} [includes=[]] - An array of includes.
  22799. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22800. */
  22801. constructor( code = '', includes = [], language = '' ) {
  22802. super( 'code' );
  22803. /**
  22804. * This flag can be used for type testing.
  22805. *
  22806. * @type {Boolean}
  22807. * @readonly
  22808. * @default true
  22809. */
  22810. this.isCodeNode = true;
  22811. /**
  22812. * The native code.
  22813. *
  22814. * @type {String}
  22815. * @default ''
  22816. */
  22817. this.code = code;
  22818. /**
  22819. * An array of includes
  22820. *
  22821. * @type {Array<Node>}
  22822. * @default []
  22823. */
  22824. this.includes = includes;
  22825. /**
  22826. * The used language.
  22827. *
  22828. * @type {('js'|'wgsl'|'glsl')}
  22829. * @default ''
  22830. */
  22831. this.language = language;
  22832. }
  22833. /**
  22834. * The method is overwritten so it always returns `true`.
  22835. *
  22836. * @return {Boolean} Whether this node is global or not.
  22837. */
  22838. isGlobal() {
  22839. return true;
  22840. }
  22841. /**
  22842. * Sets the includes of this code node.
  22843. *
  22844. * @param {Array<Node>} includes - The includes to set.
  22845. * @return {CodeNode} A reference to this node.
  22846. */
  22847. setIncludes( includes ) {
  22848. this.includes = includes;
  22849. return this;
  22850. }
  22851. /**
  22852. * Returns the includes of this code node.
  22853. *
  22854. * @param {NodeBuilder} builder - The current node builder.
  22855. * @return {Array<Node>} The includes.
  22856. */
  22857. getIncludes( /*builder*/ ) {
  22858. return this.includes;
  22859. }
  22860. generate( builder ) {
  22861. const includes = this.getIncludes( builder );
  22862. for ( const include of includes ) {
  22863. include.build( builder );
  22864. }
  22865. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22866. nodeCode.code = this.code;
  22867. return nodeCode.code;
  22868. }
  22869. serialize( data ) {
  22870. super.serialize( data );
  22871. data.code = this.code;
  22872. data.language = this.language;
  22873. }
  22874. deserialize( data ) {
  22875. super.deserialize( data );
  22876. this.code = data.code;
  22877. this.language = data.language;
  22878. }
  22879. }
  22880. /**
  22881. * TSL function for creating a code node.
  22882. *
  22883. * @function
  22884. * @param {String} [code=''] - The native code.
  22885. * @param {Array<Node>} [includes=[]] - An array of includes.
  22886. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22887. * @returns {CodeNode}
  22888. */
  22889. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22890. /**
  22891. * TSL function for creating a JS code node.
  22892. *
  22893. * @function
  22894. * @param {String} src - The native code.
  22895. * @param {Array<Node>} includes - An array of includes.
  22896. * @returns {CodeNode}
  22897. */
  22898. const js = ( src, includes ) => code( src, includes, 'js' );
  22899. /**
  22900. * TSL function for creating a WGSL code node.
  22901. *
  22902. * @function
  22903. * @param {String} src - The native code.
  22904. * @param {Array<Node>} includes - An array of includes.
  22905. * @returns {CodeNode}
  22906. */
  22907. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22908. /**
  22909. * TSL function for creating a GLSL code node.
  22910. *
  22911. * @function
  22912. * @param {String} src - The native code.
  22913. * @param {Array<Node>} includes - An array of includes.
  22914. * @returns {CodeNode}
  22915. */
  22916. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22917. /**
  22918. * This class represents a native shader function. It can be used to implement
  22919. * certain aspects of a node material with native shader code. There are two predefined
  22920. * TSL functions for easier usage.
  22921. *
  22922. * - `wgslFn`: Creates a WGSL function node.
  22923. * - `glslFn`: Creates a GLSL function node.
  22924. *
  22925. * A basic example with one include looks like so:
  22926. *
  22927. * ```js
  22928. * const desaturateWGSLFn = wgslFn( `
  22929. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22930. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22931. * return vec3<f32>( dot( lum, color ) );
  22932. * }`
  22933. *);
  22934. * const someWGSLFn = wgslFn( `
  22935. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22936. * return desaturate( color );
  22937. * }
  22938. * `, [ desaturateWGSLFn ] );
  22939. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22940. *```
  22941. * @augments CodeNode
  22942. */
  22943. class FunctionNode extends CodeNode {
  22944. static get type() {
  22945. return 'FunctionNode';
  22946. }
  22947. /**
  22948. * Constructs a new function node.
  22949. *
  22950. * @param {String} [code=''] - The native code.
  22951. * @param {Array<Node>} [includes=[]] - An array of includes.
  22952. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22953. */
  22954. constructor( code = '', includes = [], language = '' ) {
  22955. super( code, includes, language );
  22956. }
  22957. getNodeType( builder ) {
  22958. return this.getNodeFunction( builder ).type;
  22959. }
  22960. /**
  22961. * Returns the inputs of this function node.
  22962. *
  22963. * @param {NodeBuilder} builder - The current node builder.
  22964. * @return {Array<NodeFunctionInput>} The inputs.
  22965. */
  22966. getInputs( builder ) {
  22967. return this.getNodeFunction( builder ).inputs;
  22968. }
  22969. /**
  22970. * Returns the node function for this function node.
  22971. *
  22972. * @param {NodeBuilder} builder - The current node builder.
  22973. * @return {NodeFunction} The node function.
  22974. */
  22975. getNodeFunction( builder ) {
  22976. const nodeData = builder.getDataFromNode( this );
  22977. let nodeFunction = nodeData.nodeFunction;
  22978. if ( nodeFunction === undefined ) {
  22979. nodeFunction = builder.parser.parseFunction( this.code );
  22980. nodeData.nodeFunction = nodeFunction;
  22981. }
  22982. return nodeFunction;
  22983. }
  22984. generate( builder, output ) {
  22985. super.generate( builder );
  22986. const nodeFunction = this.getNodeFunction( builder );
  22987. const name = nodeFunction.name;
  22988. const type = nodeFunction.type;
  22989. const nodeCode = builder.getCodeFromNode( this, type );
  22990. if ( name !== '' ) {
  22991. // use a custom property name
  22992. nodeCode.name = name;
  22993. }
  22994. const propertyName = builder.getPropertyName( nodeCode );
  22995. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22996. nodeCode.code = code + '\n';
  22997. if ( output === 'property' ) {
  22998. return propertyName;
  22999. } else {
  23000. return builder.format( `${ propertyName }()`, type, output );
  23001. }
  23002. }
  23003. }
  23004. const nativeFn = ( code, includes = [], language = '' ) => {
  23005. for ( let i = 0; i < includes.length; i ++ ) {
  23006. const include = includes[ i ];
  23007. // TSL Function: glslFn, wgslFn
  23008. if ( typeof include === 'function' ) {
  23009. includes[ i ] = include.functionNode;
  23010. }
  23011. }
  23012. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23013. const fn = ( ...params ) => functionNode.call( ...params );
  23014. fn.functionNode = functionNode;
  23015. return fn;
  23016. };
  23017. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23018. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23019. /** @module ScriptableValueNode **/
  23020. /**
  23021. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23022. *
  23023. * @augments Node
  23024. */
  23025. class ScriptableValueNode extends Node {
  23026. static get type() {
  23027. return 'ScriptableValueNode';
  23028. }
  23029. /**
  23030. * Constructs a new scriptable node.
  23031. *
  23032. * @param {Any} [value=null] - The value.
  23033. */
  23034. constructor( value = null ) {
  23035. super();
  23036. /**
  23037. * A reference to the value.
  23038. *
  23039. * @private
  23040. * @default null
  23041. */
  23042. this._value = value;
  23043. /**
  23044. * Depending on the type of `_value`, this property might cache parsed data.
  23045. *
  23046. * @private
  23047. * @default null
  23048. */
  23049. this._cache = null;
  23050. /**
  23051. * If this node represents an input, this property represents the input type.
  23052. *
  23053. * @type {String?}
  23054. * @default null
  23055. */
  23056. this.inputType = null;
  23057. /**
  23058. * If this node represents an output, this property represents the output type.
  23059. *
  23060. * @type {String?}
  23061. * @default null
  23062. */
  23063. this.outputType = null;
  23064. /**
  23065. * An event dispatcher for managing events.
  23066. *
  23067. * @type {EventDispatcher}
  23068. */
  23069. this.events = new EventDispatcher();
  23070. /**
  23071. * This flag can be used for type testing.
  23072. *
  23073. * @type {Boolean}
  23074. * @readonly
  23075. * @default true
  23076. */
  23077. this.isScriptableValueNode = true;
  23078. }
  23079. /**
  23080. * Whether this node represents an output or not.
  23081. *
  23082. * @type {Boolean}
  23083. * @readonly
  23084. * @default true
  23085. */
  23086. get isScriptableOutputNode() {
  23087. return this.outputType !== null;
  23088. }
  23089. set value( val ) {
  23090. if ( this._value === val ) return;
  23091. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23092. URL.revokeObjectURL( this._cache );
  23093. this._cache = null;
  23094. }
  23095. this._value = val;
  23096. this.events.dispatchEvent( { type: 'change' } );
  23097. this.refresh();
  23098. }
  23099. /**
  23100. * The node's value.
  23101. *
  23102. * @type {Any}
  23103. */
  23104. get value() {
  23105. return this._value;
  23106. }
  23107. /**
  23108. * Dispatches the `refresh` event.
  23109. */
  23110. refresh() {
  23111. this.events.dispatchEvent( { type: 'refresh' } );
  23112. }
  23113. /**
  23114. * The `value` property usually represents a node or even binary data in form of array buffers.
  23115. * In this case, this method tries to return the actual value behind the complex type.
  23116. *
  23117. * @return {Any} The value.
  23118. */
  23119. getValue() {
  23120. const value = this.value;
  23121. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23122. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23123. } else if ( value && value.value !== null && value.value !== undefined && (
  23124. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23125. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23126. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23127. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23128. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23129. ( this.inputType === 'Color' && value.value.isColor ) ||
  23130. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23131. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23132. ) ) {
  23133. return value.value;
  23134. }
  23135. return this._cache || value;
  23136. }
  23137. /**
  23138. * Overwritten since the node type is inferred from the value.
  23139. *
  23140. * @param {NodeBuilder} builder - The current node builder.
  23141. * @return {String} The node type.
  23142. */
  23143. getNodeType( builder ) {
  23144. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23145. }
  23146. setup() {
  23147. return this.value && this.value.isNode ? this.value : float();
  23148. }
  23149. serialize( data ) {
  23150. super.serialize( data );
  23151. if ( this.value !== null ) {
  23152. if ( this.inputType === 'ArrayBuffer' ) {
  23153. data.value = arrayBufferToBase64( this.value );
  23154. } else {
  23155. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23156. }
  23157. } else {
  23158. data.value = null;
  23159. }
  23160. data.inputType = this.inputType;
  23161. data.outputType = this.outputType;
  23162. }
  23163. deserialize( data ) {
  23164. super.deserialize( data );
  23165. let value = null;
  23166. if ( data.value !== null ) {
  23167. if ( data.inputType === 'ArrayBuffer' ) {
  23168. value = base64ToArrayBuffer( data.value );
  23169. } else if ( data.inputType === 'Texture' ) {
  23170. value = data.meta.textures[ data.value ];
  23171. } else {
  23172. value = data.meta.nodes[ data.value ] || null;
  23173. }
  23174. }
  23175. this.value = value;
  23176. this.inputType = data.inputType;
  23177. this.outputType = data.outputType;
  23178. }
  23179. }
  23180. /**
  23181. * TSL function for creating a scriptable value node.
  23182. *
  23183. * @function
  23184. * @param {Any} [value=null] - The value.
  23185. * @returns {ScriptableValueNode}
  23186. */
  23187. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23188. /** @module ScriptableNode **/
  23189. /**
  23190. * A Map-like data structure for managing resources of scriptable nodes.
  23191. *
  23192. * @augments Map
  23193. */
  23194. class Resources extends Map {
  23195. get( key, callback = null, ...params ) {
  23196. if ( this.has( key ) ) return super.get( key );
  23197. if ( callback !== null ) {
  23198. const value = callback( ...params );
  23199. this.set( key, value );
  23200. return value;
  23201. }
  23202. }
  23203. }
  23204. class Parameters {
  23205. constructor( scriptableNode ) {
  23206. this.scriptableNode = scriptableNode;
  23207. }
  23208. get parameters() {
  23209. return this.scriptableNode.parameters;
  23210. }
  23211. get layout() {
  23212. return this.scriptableNode.getLayout();
  23213. }
  23214. getInputLayout( id ) {
  23215. return this.scriptableNode.getInputLayout( id );
  23216. }
  23217. get( name ) {
  23218. const param = this.parameters[ name ];
  23219. const value = param ? param.getValue() : null;
  23220. return value;
  23221. }
  23222. }
  23223. /**
  23224. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23225. *
  23226. * @type {Resources}
  23227. */
  23228. const ScriptableNodeResources = new Resources();
  23229. /**
  23230. * This type of node allows to implement nodes with custom scripts. The script
  23231. * section is represented as an instance of `CodeNode` written with JavaScript.
  23232. * The script itself must adhere to a specific structure.
  23233. *
  23234. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23235. * - layout: The layout object defines the script's interface (inputs and outputs).
  23236. *
  23237. * ```js
  23238. * ScriptableNodeResources.set( 'TSL', TSL );
  23239. *
  23240. * const scriptableNode = scriptable( js( `
  23241. * layout = {
  23242. * outputType: 'node',
  23243. * elements: [
  23244. * { name: 'source', inputType: 'node' },
  23245. * ]
  23246. * };
  23247. *
  23248. * const { mul, oscSine } = TSL;
  23249. *
  23250. * function main() {
  23251. * const source = parameters.get( 'source' ) || float();
  23252. * return mul( source, oscSine() ) );
  23253. * }
  23254. *
  23255. * ` ) );
  23256. *
  23257. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23258. *
  23259. * const material = new THREE.MeshBasicNodeMaterial();
  23260. * material.colorNode = scriptableNode;
  23261. * ```
  23262. *
  23263. * @augments Node
  23264. */
  23265. class ScriptableNode extends Node {
  23266. static get type() {
  23267. return 'ScriptableNode';
  23268. }
  23269. /**
  23270. * Constructs a new scriptable node.
  23271. *
  23272. * @param {CodeNode?} [codeNode=null] - The code node.
  23273. * @param {Object} [parameters={}] - The parameters definition.
  23274. */
  23275. constructor( codeNode = null, parameters = {} ) {
  23276. super();
  23277. /**
  23278. * The code node.
  23279. *
  23280. * @type {CodeNode?}
  23281. * @default null
  23282. */
  23283. this.codeNode = codeNode;
  23284. /**
  23285. * The parameters definition.
  23286. *
  23287. * @type {Object}
  23288. * @default {}
  23289. */
  23290. this.parameters = parameters;
  23291. this._local = new Resources();
  23292. this._output = scriptableValue();
  23293. this._outputs = {};
  23294. this._source = this.source;
  23295. this._method = null;
  23296. this._object = null;
  23297. this._value = null;
  23298. this._needsOutputUpdate = true;
  23299. this.onRefresh = this.onRefresh.bind( this );
  23300. /**
  23301. * This flag can be used for type testing.
  23302. *
  23303. * @type {Boolean}
  23304. * @readonly
  23305. * @default true
  23306. */
  23307. this.isScriptableNode = true;
  23308. }
  23309. /**
  23310. * The source code of the scriptable node.
  23311. *
  23312. * @type {String}
  23313. */
  23314. get source() {
  23315. return this.codeNode ? this.codeNode.code : '';
  23316. }
  23317. /**
  23318. * Sets the reference of a local script variable.
  23319. *
  23320. * @param {String} name - The variable name.
  23321. * @param {Object} value - The reference to set.
  23322. * @return {Resources} The resource map
  23323. */
  23324. setLocal( name, value ) {
  23325. return this._local.set( name, value );
  23326. }
  23327. /**
  23328. * Gets the value of a local script variable.
  23329. *
  23330. * @param {String} name - The variable name.
  23331. * @return {Object} The value.
  23332. */
  23333. getLocal( name ) {
  23334. return this._local.get( name );
  23335. }
  23336. /**
  23337. * Event listener for the `refresh` event.
  23338. */
  23339. onRefresh() {
  23340. this._refresh();
  23341. }
  23342. /**
  23343. * Returns an input from the layout with the given id/name.
  23344. *
  23345. * @param {String} id - The id/name of the input.
  23346. * @return {Object} The element entry.
  23347. */
  23348. getInputLayout( id ) {
  23349. for ( const element of this.getLayout() ) {
  23350. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23351. return element;
  23352. }
  23353. }
  23354. }
  23355. /**
  23356. * Returns an output from the layout with the given id/name.
  23357. *
  23358. * @param {String} id - The id/name of the output.
  23359. * @return {Object} The element entry.
  23360. */
  23361. getOutputLayout( id ) {
  23362. for ( const element of this.getLayout() ) {
  23363. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23364. return element;
  23365. }
  23366. }
  23367. }
  23368. /**
  23369. * Defines a script output for the given name and value.
  23370. *
  23371. * @param {String} name - The name of the output.
  23372. * @param {Node} value - The node value.
  23373. * @return {ScriptableNode} A reference to this node.
  23374. */
  23375. setOutput( name, value ) {
  23376. const outputs = this._outputs;
  23377. if ( outputs[ name ] === undefined ) {
  23378. outputs[ name ] = scriptableValue( value );
  23379. } else {
  23380. outputs[ name ].value = value;
  23381. }
  23382. return this;
  23383. }
  23384. /**
  23385. * Returns a script output for the given name.
  23386. *
  23387. * @param {String} name - The name of the output.
  23388. * @return {ScriptableValueNode} The node value.
  23389. */
  23390. getOutput( name ) {
  23391. return this._outputs[ name ];
  23392. }
  23393. /**
  23394. * Returns a parameter for the given name
  23395. *
  23396. * @param {String} name - The name of the parameter.
  23397. * @return {ScriptableValueNode} The node value.
  23398. */
  23399. getParameter( name ) {
  23400. return this.parameters[ name ];
  23401. }
  23402. /**
  23403. * Sets a value for the given parameter name.
  23404. *
  23405. * @param {String} name - The parameter name.
  23406. * @param {Any} value - The parameter value.
  23407. * @return {ScriptableNode} A reference to this node.
  23408. */
  23409. setParameter( name, value ) {
  23410. const parameters = this.parameters;
  23411. if ( value && value.isScriptableNode ) {
  23412. this.deleteParameter( name );
  23413. parameters[ name ] = value;
  23414. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23415. } else if ( value && value.isScriptableValueNode ) {
  23416. this.deleteParameter( name );
  23417. parameters[ name ] = value;
  23418. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23419. } else if ( parameters[ name ] === undefined ) {
  23420. parameters[ name ] = scriptableValue( value );
  23421. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23422. } else {
  23423. parameters[ name ].value = value;
  23424. }
  23425. return this;
  23426. }
  23427. /**
  23428. * Returns the value of this node which is the value of
  23429. * the default output.
  23430. *
  23431. * @return {Node} The value.
  23432. */
  23433. getValue() {
  23434. return this.getDefaultOutput().getValue();
  23435. }
  23436. /**
  23437. * Deletes a parameter from the script.
  23438. *
  23439. * @param {String} name - The parameter to remove.
  23440. * @return {ScriptableNode} A reference to this node.
  23441. */
  23442. deleteParameter( name ) {
  23443. let valueNode = this.parameters[ name ];
  23444. if ( valueNode ) {
  23445. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23446. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23447. }
  23448. return this;
  23449. }
  23450. /**
  23451. * Deletes all parameters from the script.
  23452. *
  23453. * @return {ScriptableNode} A reference to this node.
  23454. */
  23455. clearParameters() {
  23456. for ( const name of Object.keys( this.parameters ) ) {
  23457. this.deleteParameter( name );
  23458. }
  23459. this.needsUpdate = true;
  23460. return this;
  23461. }
  23462. /**
  23463. * Calls a function from the script.
  23464. *
  23465. * @param {String} name - The function name.
  23466. * @param {...Any} params - A list of parameters.
  23467. * @return {Any} The result of the function call.
  23468. */
  23469. call( name, ...params ) {
  23470. const object = this.getObject();
  23471. const method = object[ name ];
  23472. if ( typeof method === 'function' ) {
  23473. return method( ...params );
  23474. }
  23475. }
  23476. /**
  23477. * Asynchronously calls a function from the script.
  23478. *
  23479. * @param {String} name - The function name.
  23480. * @param {...Any} params - A list of parameters.
  23481. * @return {Promise<Any>} The result of the function call.
  23482. */
  23483. async callAsync( name, ...params ) {
  23484. const object = this.getObject();
  23485. const method = object[ name ];
  23486. if ( typeof method === 'function' ) {
  23487. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23488. }
  23489. }
  23490. /**
  23491. * Overwritten since the node types is inferred from the script's output.
  23492. *
  23493. * @param {NodeBuilder} builder - The current node builder
  23494. * @return {String} The node type.
  23495. */
  23496. getNodeType( builder ) {
  23497. return this.getDefaultOutputNode().getNodeType( builder );
  23498. }
  23499. /**
  23500. * Refreshes the script node.
  23501. *
  23502. * @param {String?} [output=null] - An optional output.
  23503. */
  23504. refresh( output = null ) {
  23505. if ( output !== null ) {
  23506. this.getOutput( output ).refresh();
  23507. } else {
  23508. this._refresh();
  23509. }
  23510. }
  23511. /**
  23512. * Returns an object representation of the script.
  23513. *
  23514. * @return {Object} The result object.
  23515. */
  23516. getObject() {
  23517. if ( this.needsUpdate ) this.dispose();
  23518. if ( this._object !== null ) return this._object;
  23519. //
  23520. const refresh = () => this.refresh();
  23521. const setOutput = ( id, value ) => this.setOutput( id, value );
  23522. const parameters = new Parameters( this );
  23523. const THREE = ScriptableNodeResources.get( 'THREE' );
  23524. const TSL = ScriptableNodeResources.get( 'TSL' );
  23525. const method = this.getMethod();
  23526. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23527. this._object = method( ...params );
  23528. const layout = this._object.layout;
  23529. if ( layout ) {
  23530. if ( layout.cache === false ) {
  23531. this._local.clear();
  23532. }
  23533. // default output
  23534. this._output.outputType = layout.outputType || null;
  23535. if ( Array.isArray( layout.elements ) ) {
  23536. for ( const element of layout.elements ) {
  23537. const id = element.id || element.name;
  23538. if ( element.inputType ) {
  23539. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23540. this.getParameter( id ).inputType = element.inputType;
  23541. }
  23542. if ( element.outputType ) {
  23543. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23544. this.getOutput( id ).outputType = element.outputType;
  23545. }
  23546. }
  23547. }
  23548. }
  23549. return this._object;
  23550. }
  23551. deserialize( data ) {
  23552. super.deserialize( data );
  23553. for ( const name in this.parameters ) {
  23554. let valueNode = this.parameters[ name ];
  23555. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23556. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23557. }
  23558. }
  23559. /**
  23560. * Returns the layout of the script.
  23561. *
  23562. * @return {Object} The script's layout.
  23563. */
  23564. getLayout() {
  23565. return this.getObject().layout;
  23566. }
  23567. /**
  23568. * Returns default node output of the script.
  23569. *
  23570. * @return {Node} The default node output.
  23571. */
  23572. getDefaultOutputNode() {
  23573. const output = this.getDefaultOutput().value;
  23574. if ( output && output.isNode ) {
  23575. return output;
  23576. }
  23577. return float();
  23578. }
  23579. /**
  23580. * Returns default output of the script.
  23581. *
  23582. * @return {ScriptableValueNode} The default output.
  23583. */
  23584. getDefaultOutput() {
  23585. return this._exec()._output;
  23586. }
  23587. /**
  23588. * Returns a function created from the node's script.
  23589. *
  23590. * @return {Function} The function representing the node's code.
  23591. */
  23592. getMethod() {
  23593. if ( this.needsUpdate ) this.dispose();
  23594. if ( this._method !== null ) return this._method;
  23595. //
  23596. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23597. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23598. const properties = interfaceProps.join( ', ' );
  23599. const declarations = 'var ' + properties + '; var output = {};\n';
  23600. const returns = '\nreturn { ...output, ' + properties + ' };';
  23601. const code = declarations + this.codeNode.code + returns;
  23602. //
  23603. this._method = new Function( ...parametersProps, code );
  23604. return this._method;
  23605. }
  23606. /**
  23607. * Frees all internal resources.
  23608. */
  23609. dispose() {
  23610. if ( this._method === null ) return;
  23611. if ( this._object && typeof this._object.dispose === 'function' ) {
  23612. this._object.dispose();
  23613. }
  23614. this._method = null;
  23615. this._object = null;
  23616. this._source = null;
  23617. this._value = null;
  23618. this._needsOutputUpdate = true;
  23619. this._output.value = null;
  23620. this._outputs = {};
  23621. }
  23622. setup() {
  23623. return this.getDefaultOutputNode();
  23624. }
  23625. getCacheKey( force ) {
  23626. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23627. for ( const param in this.parameters ) {
  23628. values.push( this.parameters[ param ].getCacheKey( force ) );
  23629. }
  23630. return hashArray( values );
  23631. }
  23632. set needsUpdate( value ) {
  23633. if ( value === true ) this.dispose();
  23634. }
  23635. get needsUpdate() {
  23636. return this.source !== this._source;
  23637. }
  23638. /**
  23639. * Executes the `main` function of the script.
  23640. *
  23641. * @private
  23642. * @return {ScriptableNode} A reference to this node.
  23643. */
  23644. _exec() {
  23645. if ( this.codeNode === null ) return this;
  23646. if ( this._needsOutputUpdate === true ) {
  23647. this._value = this.call( 'main' );
  23648. this._needsOutputUpdate = false;
  23649. }
  23650. this._output.value = this._value;
  23651. return this;
  23652. }
  23653. /**
  23654. * Executes the refresh.
  23655. *
  23656. * @private
  23657. */
  23658. _refresh() {
  23659. this.needsUpdate = true;
  23660. this._exec();
  23661. this._output.refresh();
  23662. }
  23663. }
  23664. /**
  23665. * TSL function for creating a scriptable node.
  23666. *
  23667. * @function
  23668. * @param {CodeNode?} [codeNode=null] - The code node.
  23669. * @param {Object} [parameters={}] - The parameters definition.
  23670. * @returns {ScriptableNode}
  23671. */
  23672. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23673. /** @module Fog **/
  23674. /**
  23675. * Returns a node that represents the `z` coordinate in view space
  23676. * for the current fragment. It's a different representation of the
  23677. * default depth value.
  23678. *
  23679. * This value can be part of a computation that defines how the fog
  23680. * density increases when moving away from the camera.
  23681. *
  23682. * @param {NodeBuilder} builder - The current node builder.
  23683. * @return {Node} The viewZ node.
  23684. */
  23685. function getViewZNode( builder ) {
  23686. let viewZ;
  23687. const getViewZ = builder.context.getViewZ;
  23688. if ( getViewZ !== undefined ) {
  23689. viewZ = getViewZ( this );
  23690. }
  23691. return ( viewZ || positionView.z ).negate();
  23692. }
  23693. /**
  23694. * Constructs a new range factor node.
  23695. *
  23696. * @function
  23697. * @param {Node} near - Defines the near value.
  23698. * @param {Node} far - Defines the far value.
  23699. */
  23700. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23701. const viewZ = getViewZNode( builder );
  23702. return smoothstep( near, far, viewZ );
  23703. } );
  23704. /**
  23705. * Represents an exponential squared fog. This type of fog gives
  23706. * a clear view near the camera and a faster than exponentially
  23707. * densening fog farther from the camera.
  23708. *
  23709. * @function
  23710. * @param {Node} density - Defines the fog density.
  23711. */
  23712. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23713. const viewZ = getViewZNode( builder );
  23714. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23715. } );
  23716. /**
  23717. * This class can be used to configure a fog for the scene.
  23718. * Nodes of this type are assigned to `Scene.fogNode`.
  23719. *
  23720. * @function
  23721. * @param {Node} color - Defines the color of the fog.
  23722. * @param {Node} factor - Defines how the fog is factored in the scene.
  23723. */
  23724. const fog = Fn( ( [ color, factor ] ) => {
  23725. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23726. } );
  23727. // Deprecated
  23728. /**
  23729. * @function
  23730. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23731. *
  23732. * @param {Node} color
  23733. * @param {Node} near
  23734. * @param {Node} far
  23735. * @returns {Function}
  23736. */
  23737. function rangeFog( color, near, far ) { // @deprecated, r171
  23738. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23739. return fog( color, rangeFogFactor( near, far ) );
  23740. }
  23741. /**
  23742. * @function
  23743. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23744. *
  23745. * @param {Node} color
  23746. * @param {Node} density
  23747. * @returns {Function}
  23748. */
  23749. function densityFog( color, density ) { // @deprecated, r171
  23750. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23751. return fog( color, densityFogFactor( density ) );
  23752. }
  23753. /** @module RangeNode **/
  23754. let min = null;
  23755. let max = null;
  23756. /**
  23757. * `RangeNode` generates random instanced attribute data in a defined range.
  23758. * An exemplary use case for this utility node is to generate random per-instance
  23759. * colors:
  23760. * ```js
  23761. * const material = new MeshBasicNodeMaterial();
  23762. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23763. * const mesh = new InstancedMesh( geometry, material, count );
  23764. * ```
  23765. * @augments Node
  23766. */
  23767. class RangeNode extends Node {
  23768. static get type() {
  23769. return 'RangeNode';
  23770. }
  23771. /**
  23772. * Constructs a new range node.
  23773. *
  23774. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23775. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23776. */
  23777. constructor( minNode = float(), maxNode = float() ) {
  23778. super();
  23779. /**
  23780. * A node defining the lower bound of the range.
  23781. *
  23782. * @type {Node<any>}
  23783. * @default float()
  23784. */
  23785. this.minNode = minNode;
  23786. /**
  23787. * A node defining the upper bound of the range.
  23788. *
  23789. * @type {Node<any>}
  23790. * @default float()
  23791. */
  23792. this.maxNode = maxNode;
  23793. }
  23794. /**
  23795. * Returns the vector length which is computed based on the range definition.
  23796. *
  23797. * @param {NodeBuilder} builder - The current node builder.
  23798. * @return {Number} The vector length.
  23799. */
  23800. getVectorLength( builder ) {
  23801. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23802. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23803. return minLength > maxLength ? minLength : maxLength;
  23804. }
  23805. /**
  23806. * This method is overwritten since the node type is inferred from range definition.
  23807. *
  23808. * @param {NodeBuilder} builder - The current node builder.
  23809. * @return {String} The node type.
  23810. */
  23811. getNodeType( builder ) {
  23812. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23813. }
  23814. setup( builder ) {
  23815. const object = builder.object;
  23816. let output = null;
  23817. if ( object.count > 1 ) {
  23818. const minValue = this.minNode.value;
  23819. const maxValue = this.maxNode.value;
  23820. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23821. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23822. min = min || new Vector4();
  23823. max = max || new Vector4();
  23824. min.setScalar( 0 );
  23825. max.setScalar( 0 );
  23826. if ( minLength === 1 ) min.setScalar( minValue );
  23827. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23828. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23829. if ( maxLength === 1 ) max.setScalar( maxValue );
  23830. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23831. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23832. const stride = 4;
  23833. const length = stride * object.count;
  23834. const array = new Float32Array( length );
  23835. for ( let i = 0; i < length; i ++ ) {
  23836. const index = i % stride;
  23837. const minElementValue = min.getComponent( index );
  23838. const maxElementValue = max.getComponent( index );
  23839. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23840. }
  23841. const nodeType = this.getNodeType( builder );
  23842. if ( object.count <= 4096 ) {
  23843. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23844. } else {
  23845. // TODO: Improve anonymous buffer attribute creation removing this part
  23846. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23847. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23848. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23849. }
  23850. } else {
  23851. output = float( 0 );
  23852. }
  23853. return output;
  23854. }
  23855. }
  23856. /**
  23857. * TSL function for creating a range node.
  23858. *
  23859. * @function
  23860. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23861. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23862. * @returns {RangeNode}
  23863. */
  23864. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23865. /** @module ComputeBuiltinNode **/
  23866. /**
  23867. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23868. * about the currently running dispatch and/or the device it is running on.
  23869. *
  23870. * This node can only be used with a WebGPU backend.
  23871. *
  23872. * @augments Node
  23873. */
  23874. class ComputeBuiltinNode extends Node {
  23875. static get type() {
  23876. return 'ComputeBuiltinNode';
  23877. }
  23878. /**
  23879. * Constructs a new compute builtin node.
  23880. *
  23881. * @param {String} builtinName - The built-in name.
  23882. * @param {String} nodeType - The node type.
  23883. */
  23884. constructor( builtinName, nodeType ) {
  23885. super( nodeType );
  23886. /**
  23887. * The built-in name.
  23888. *
  23889. * @private
  23890. * @type {String}
  23891. */
  23892. this._builtinName = builtinName;
  23893. }
  23894. /**
  23895. * This method is overwritten since hash is derived from the built-in name.
  23896. *
  23897. * @param {NodeBuilder} builder - The current node builder.
  23898. * @return {String} The hash.
  23899. */
  23900. getHash( builder ) {
  23901. return this.getBuiltinName( builder );
  23902. }
  23903. /**
  23904. * This method is overwritten since the node type is simply derived from `nodeType`..
  23905. *
  23906. * @param {NodeBuilder} builder - The current node builder.
  23907. * @return {String} The node type.
  23908. */
  23909. getNodeType( /*builder*/ ) {
  23910. return this.nodeType;
  23911. }
  23912. /**
  23913. * Sets the builtin name.
  23914. *
  23915. * @param {String} builtinName - The built-in name.
  23916. * @return {ComputeBuiltinNode} A reference to this node.
  23917. */
  23918. setBuiltinName( builtinName ) {
  23919. this._builtinName = builtinName;
  23920. return this;
  23921. }
  23922. /**
  23923. * Returns the builtin name.
  23924. *
  23925. * @param {NodeBuilder} builder - The current node builder.
  23926. * @return {String} The builtin name.
  23927. */
  23928. getBuiltinName( /*builder*/ ) {
  23929. return this._builtinName;
  23930. }
  23931. /**
  23932. * Whether the current node builder has the builtin or not.
  23933. *
  23934. * @param {NodeBuilder} builder - The current node builder.
  23935. */
  23936. hasBuiltin( builder ) {
  23937. builder.hasBuiltin( this._builtinName );
  23938. }
  23939. generate( builder, output ) {
  23940. const builtinName = this.getBuiltinName( builder );
  23941. const nodeType = this.getNodeType( builder );
  23942. if ( builder.shaderStage === 'compute' ) {
  23943. return builder.format( builtinName, nodeType, output );
  23944. } else {
  23945. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23946. return builder.generateConst( nodeType );
  23947. }
  23948. }
  23949. serialize( data ) {
  23950. super.serialize( data );
  23951. data.global = this.global;
  23952. data._builtinName = this._builtinName;
  23953. }
  23954. deserialize( data ) {
  23955. super.deserialize( data );
  23956. this.global = data.global;
  23957. this._builtinName = data._builtinName;
  23958. }
  23959. }
  23960. /**
  23961. * TSL function for creating a compute builtin node.
  23962. *
  23963. * @function
  23964. * @param {String} name - The built-in name.
  23965. * @param {String} nodeType - The node type.
  23966. * @returns {ComputeBuiltinNode}
  23967. */
  23968. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23969. /**
  23970. * TSL function for creating a `numWorkgroups` builtin node.
  23971. * Represents the number of workgroups dispatched by the compute shader.
  23972. * ```js
  23973. * // Run 512 invocations/threads with a workgroup size of 128.
  23974. * const computeFn = Fn(() => {
  23975. *
  23976. * // numWorkgroups.x = 4
  23977. * storageBuffer.element(0).assign(numWorkgroups.x)
  23978. *
  23979. * })().compute(512, [128]);
  23980. *
  23981. * // Run 512 invocations/threads with the default workgroup size of 64.
  23982. * const computeFn = Fn(() => {
  23983. *
  23984. * // numWorkgroups.x = 8
  23985. * storageBuffer.element(0).assign(numWorkgroups.x)
  23986. *
  23987. * })().compute(512);
  23988. * ```
  23989. *
  23990. * @function
  23991. * @returns {ComputeBuiltinNode<uvec3>}
  23992. */
  23993. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23994. /**
  23995. * TSL function for creating a `workgroupId` builtin node.
  23996. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23997. * ```js
  23998. * // Execute 12 compute threads with a workgroup size of 3.
  23999. * const computeFn = Fn( () => {
  24000. *
  24001. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24002. *
  24003. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24004. *
  24005. * } ).Else( () => {
  24006. *
  24007. * storageBuffer.element( instanceIndex ).assign( 0 );
  24008. *
  24009. * } );
  24010. *
  24011. * } )().compute( 12, [ 3 ] );
  24012. *
  24013. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24014. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24015. * ```
  24016. *
  24017. * @function
  24018. * @returns {ComputeBuiltinNode<uvec3>}
  24019. */
  24020. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24021. /**
  24022. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24023. * representation of the current invocation's position within a 3D global grid.
  24024. *
  24025. * @function
  24026. * @returns {ComputeBuiltinNode<uvec3>}
  24027. */
  24028. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24029. /**
  24030. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24031. * representation of the current invocation's position within a 3D workgroup grid.
  24032. *
  24033. * @function
  24034. * @returns {ComputeBuiltinNode<uvec3>}
  24035. */
  24036. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24037. /**
  24038. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24039. * that exposes the size of the current invocation's subgroup.
  24040. *
  24041. * @function
  24042. * @returns {ComputeBuiltinNode<uint>}
  24043. */
  24044. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24045. /** @module BarrierNode **/
  24046. /**
  24047. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24048. *
  24049. * This node can only be used with a WebGPU backend.
  24050. *
  24051. * @augments Node
  24052. */
  24053. class BarrierNode extends Node {
  24054. /**
  24055. * Constructs a new barrier node.
  24056. *
  24057. * @param {String} scope - The scope defines the behavior of the node.
  24058. */
  24059. constructor( scope ) {
  24060. super();
  24061. this.scope = scope;
  24062. }
  24063. generate( builder ) {
  24064. const { scope } = this;
  24065. const { renderer } = builder;
  24066. if ( renderer.backend.isWebGLBackend === true ) {
  24067. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24068. } else {
  24069. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24070. }
  24071. }
  24072. }
  24073. /**
  24074. * TSL function for creating a barrier node.
  24075. *
  24076. * @function
  24077. * @param {String} scope - The scope defines the behavior of the node..
  24078. * @returns {BarrierNode}
  24079. */
  24080. const barrier = nodeProxy( BarrierNode );
  24081. /**
  24082. * TSL function for creating a workgroup barrier. All compute shader
  24083. * invocations must wait for each invocation within a workgroup to
  24084. * complete before the barrier can be surpassed.
  24085. *
  24086. * @function
  24087. * @returns {BarrierNode}
  24088. */
  24089. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24090. /**
  24091. * TSL function for creating a storage barrier. All invocations must
  24092. * wait for each access to variables within the 'storage' address space
  24093. * to complete before the barrier can be passed.
  24094. *
  24095. * @function
  24096. * @returns {BarrierNode}
  24097. */
  24098. const storageBarrier = () => barrier( 'storage' ).append();
  24099. /**
  24100. * TSL function for creating a texture barrier. All invocations must
  24101. * wait for each access to variables within the 'texture' address space
  24102. * to complete before the barrier can be passed.
  24103. *
  24104. * @function
  24105. * @returns {BarrierNode}
  24106. */
  24107. const textureBarrier = () => barrier( 'texture' ).append();
  24108. /** @module WorkgroupInfoNode **/
  24109. /**
  24110. * Represents an element of a 'workgroup' scoped buffer.
  24111. *
  24112. * @augments ArrayElementNode
  24113. */
  24114. class WorkgroupInfoElementNode extends ArrayElementNode {
  24115. /**
  24116. * Constructs a new workgroup info element node.
  24117. *
  24118. * @param {Node} workgroupInfoNode - The workgroup info node.
  24119. * @param {Node} indexNode - The index node that defines the element access.
  24120. */
  24121. constructor( workgroupInfoNode, indexNode ) {
  24122. super( workgroupInfoNode, indexNode );
  24123. /**
  24124. * This flag can be used for type testing.
  24125. *
  24126. * @type {Boolean}
  24127. * @readonly
  24128. * @default true
  24129. */
  24130. this.isWorkgroupInfoElementNode = true;
  24131. }
  24132. generate( builder, output ) {
  24133. let snippet;
  24134. const isAssignContext = builder.context.assign;
  24135. snippet = super.generate( builder );
  24136. if ( isAssignContext !== true ) {
  24137. const type = this.getNodeType( builder );
  24138. snippet = builder.format( snippet, type, output );
  24139. }
  24140. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24141. return snippet;
  24142. }
  24143. }
  24144. /**
  24145. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24146. * context of a compute shader. Typically, workgroup scoped buffers are
  24147. * created to hold data that is transferred from a global storage scope into
  24148. * a local workgroup scope. For invocations within a workgroup, data
  24149. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24150. * than similar access operations on globally accessible storage buffers.
  24151. *
  24152. * This node can only be used with a WebGPU backend.
  24153. *
  24154. * @augments Node
  24155. */
  24156. class WorkgroupInfoNode extends Node {
  24157. /**
  24158. * Constructs a new buffer scoped to type scope.
  24159. *
  24160. * @param {String} scope - TODO.
  24161. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24162. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24163. */
  24164. constructor( scope, bufferType, bufferCount = 0 ) {
  24165. super( bufferType );
  24166. /**
  24167. * The buffer type.
  24168. *
  24169. * @type {String}
  24170. */
  24171. this.bufferType = bufferType;
  24172. /**
  24173. * The buffer count.
  24174. *
  24175. * @type {Number}
  24176. * @default 0
  24177. */
  24178. this.bufferCount = bufferCount;
  24179. /**
  24180. * This flag can be used for type testing.
  24181. *
  24182. * @type {Boolean}
  24183. * @readonly
  24184. * @default true
  24185. */
  24186. this.isWorkgroupInfoNode = true;
  24187. /**
  24188. * The data type of the array buffer.
  24189. *
  24190. * @type {String}
  24191. */
  24192. this.elementType = bufferType;
  24193. /**
  24194. * TODO.
  24195. *
  24196. * @type {String}
  24197. */
  24198. this.scope = scope;
  24199. }
  24200. /**
  24201. * Sets the name/label of this node.
  24202. *
  24203. * @param {String} name - The name to set.
  24204. * @return {WorkgroupInfoNode} A reference to this node.
  24205. */
  24206. label( name ) {
  24207. this.name = name;
  24208. return this;
  24209. }
  24210. /**
  24211. * Sets the scope of this node.
  24212. *
  24213. * @param {String} scope - The scope to set.
  24214. * @return {WorkgroupInfoNode} A reference to this node.
  24215. */
  24216. setScope( scope ) {
  24217. this.scope = scope;
  24218. return this;
  24219. }
  24220. /**
  24221. * The data type of the array buffer.
  24222. *
  24223. * @return {String} The element type.
  24224. */
  24225. getElementType() {
  24226. return this.elementType;
  24227. }
  24228. /**
  24229. * Overwrites the default implementation since the input type
  24230. * is inferred from the scope.
  24231. *
  24232. * @param {NodeBuilder} builder - The current node builder.
  24233. * @return {String} The input type.
  24234. */
  24235. getInputType( /*builder*/ ) {
  24236. return `${this.scope}Array`;
  24237. }
  24238. /**
  24239. * This method can be used to access elements via an index node.
  24240. *
  24241. * @param {IndexNode} indexNode - indexNode.
  24242. * @return {WorkgroupInfoElementNode} A reference to an element.
  24243. */
  24244. element( indexNode ) {
  24245. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24246. }
  24247. generate( builder ) {
  24248. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24249. }
  24250. }
  24251. /**
  24252. * TSL function for creating a workgroup info node.
  24253. * Creates a new 'workgroup' scoped array buffer.
  24254. *
  24255. * @function
  24256. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24257. * @param {Number} [count=0] - The number of elements in the buffer.
  24258. * @returns {WorkgroupInfoNode}
  24259. */
  24260. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24261. /** @module AtomicFunctionNode **/
  24262. /**
  24263. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24264. * within a shader. In an atomic function, any modification to an atomic variable will
  24265. * occur as an indivisible step with a defined order relative to other modifications.
  24266. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24267. * atomic operations will not interfere with each other.
  24268. *
  24269. * This node can only be used with a WebGPU backend.
  24270. *
  24271. * @augments TempNode
  24272. */
  24273. class AtomicFunctionNode extends TempNode {
  24274. static get type() {
  24275. return 'AtomicFunctionNode';
  24276. }
  24277. /**
  24278. * Constructs a new atomic function node.
  24279. *
  24280. * @param {String} method - The signature of the atomic function to construct.
  24281. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24282. * @param {Node} valueNode - The value that mutates the atomic variable.
  24283. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24284. */
  24285. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24286. super( 'uint' );
  24287. /**
  24288. * The signature of the atomic function to construct.
  24289. *
  24290. * @type {String}
  24291. */
  24292. this.method = method;
  24293. /**
  24294. * An atomic variable or element of an atomic buffer.
  24295. *
  24296. * @type {Node}
  24297. */
  24298. this.pointerNode = pointerNode;
  24299. /**
  24300. * A value that modifies the atomic variable.
  24301. *
  24302. * @type {Node}
  24303. */
  24304. this.valueNode = valueNode;
  24305. /**
  24306. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24307. *
  24308. * @type {Node?}
  24309. * @default null
  24310. */
  24311. this.storeNode = storeNode;
  24312. }
  24313. /**
  24314. * Overwrites the default implementation to return the type of
  24315. * the pointer node.
  24316. *
  24317. * @param {NodeBuilder} builder - The current node builder.
  24318. * @return {String} The input type.
  24319. */
  24320. getInputType( builder ) {
  24321. return this.pointerNode.getNodeType( builder );
  24322. }
  24323. /**
  24324. * Overwritten since the node type is inferred from the input type.
  24325. *
  24326. * @param {NodeBuilder} builder - The current node builder.
  24327. * @return {String} The node type.
  24328. */
  24329. getNodeType( builder ) {
  24330. return this.getInputType( builder );
  24331. }
  24332. generate( builder ) {
  24333. const method = this.method;
  24334. const type = this.getNodeType( builder );
  24335. const inputType = this.getInputType( builder );
  24336. const a = this.pointerNode;
  24337. const b = this.valueNode;
  24338. const params = [];
  24339. params.push( `&${ a.build( builder, inputType ) }` );
  24340. params.push( b.build( builder, inputType ) );
  24341. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24342. if ( this.storeNode !== null ) {
  24343. const varSnippet = this.storeNode.build( builder, inputType );
  24344. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24345. } else {
  24346. builder.addLineFlowCode( methodSnippet, this );
  24347. }
  24348. }
  24349. }
  24350. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24351. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24352. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24353. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24354. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24355. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24356. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24357. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24358. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24359. /**
  24360. * TSL function for creating an atomic function node.
  24361. *
  24362. * @function
  24363. * @param {String} method - The signature of the atomic function to construct.
  24364. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24365. * @param {Node} valueNode - The value that mutates the atomic variable.
  24366. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24367. * @returns {AtomicFunctionNode}
  24368. */
  24369. const atomicNode = nodeProxy( AtomicFunctionNode );
  24370. /**
  24371. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24372. *
  24373. * @function
  24374. * @param {String} method - The signature of the atomic function to construct.
  24375. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24376. * @param {Node} valueNode - The value that mutates the atomic variable.
  24377. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24378. * @returns {AtomicFunctionNode}
  24379. */
  24380. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24381. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24382. node.append();
  24383. return node;
  24384. };
  24385. /**
  24386. * Stores a value in the atomic variable.
  24387. *
  24388. * @function
  24389. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24390. * @param {Node} valueNode - The value that mutates the atomic variable.
  24391. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24392. * @returns {AtomicFunctionNode}
  24393. */
  24394. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24395. /**
  24396. * Increments the value stored in the atomic variable.
  24397. *
  24398. * @function
  24399. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24400. * @param {Node} valueNode - The value that mutates the atomic variable.
  24401. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24402. * @returns {AtomicFunctionNode}
  24403. */
  24404. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24405. /**
  24406. * Decrements the value stored in the atomic variable.
  24407. *
  24408. * @function
  24409. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24410. * @param {Node} valueNode - The value that mutates the atomic variable.
  24411. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24412. * @returns {AtomicFunctionNode}
  24413. */
  24414. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24415. /**
  24416. * Stores in an atomic variable the maximum between its current value and a parameter.
  24417. *
  24418. * @function
  24419. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24420. * @param {Node} valueNode - The value that mutates the atomic variable.
  24421. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24422. * @returns {AtomicFunctionNode}
  24423. */
  24424. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24425. /**
  24426. * Stores in an atomic variable the minimum between its current value and a parameter.
  24427. *
  24428. * @function
  24429. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24430. * @param {Node} valueNode - The value that mutates the atomic variable.
  24431. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24432. * @returns {AtomicFunctionNode}
  24433. */
  24434. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24435. /**
  24436. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24437. *
  24438. * @function
  24439. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24440. * @param {Node} valueNode - The value that mutates the atomic variable.
  24441. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24442. * @returns {AtomicFunctionNode}
  24443. */
  24444. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24445. /**
  24446. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24447. *
  24448. * @function
  24449. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24450. * @param {Node} valueNode - The value that mutates the atomic variable.
  24451. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24452. * @returns {AtomicFunctionNode}
  24453. */
  24454. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24455. /**
  24456. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24457. *
  24458. * @function
  24459. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24460. * @param {Node} valueNode - The value that mutates the atomic variable.
  24461. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24462. * @returns {AtomicFunctionNode}
  24463. */
  24464. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24465. /** @module Lights **/
  24466. let uniformsLib;
  24467. function getLightData( light ) {
  24468. uniformsLib = uniformsLib || new WeakMap();
  24469. let uniforms = uniformsLib.get( light );
  24470. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24471. return uniforms;
  24472. }
  24473. /**
  24474. * TSL function for getting a shadow matrix uniform node for the given light.
  24475. *
  24476. * @function
  24477. * @param {Light} light -The light source.
  24478. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24479. */
  24480. function lightShadowMatrix( light ) {
  24481. const data = getLightData( light );
  24482. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24483. if ( light.castShadow !== true ) {
  24484. light.shadow.updateMatrices( light );
  24485. }
  24486. return light.shadow.matrix;
  24487. } ) );
  24488. }
  24489. /**
  24490. * TSL function for getting projected uv coordinates for the given light.
  24491. * Relevant when using maps with spot lights.
  24492. *
  24493. * @function
  24494. * @param {Light} light -The light source.
  24495. * @returns {Node<vec3>} The projected uvs.
  24496. */
  24497. function lightProjectionUV( light ) {
  24498. const data = getLightData( light );
  24499. if ( data.projectionUV === undefined ) {
  24500. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24501. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24502. }
  24503. return data.projectionUV;
  24504. }
  24505. /**
  24506. * TSL function for getting the position in world space for the given light.
  24507. *
  24508. * @function
  24509. * @param {Light} light -The light source.
  24510. * @returns {UniformNode<vec3>} The light's position in world space.
  24511. */
  24512. function lightPosition( light ) {
  24513. const data = getLightData( light );
  24514. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24515. }
  24516. /**
  24517. * TSL function for getting the light target position in world space for the given light.
  24518. *
  24519. * @function
  24520. * @param {Light} light -The light source.
  24521. * @returns {UniformNode<vec3>} The light target position in world space.
  24522. */
  24523. function lightTargetPosition( light ) {
  24524. const data = getLightData( light );
  24525. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24526. }
  24527. /**
  24528. * TSL function for getting the position in view space for the given light.
  24529. *
  24530. * @function
  24531. * @param {Light} light -The light source.
  24532. * @returns {UniformNode<vec3>} The light's position in view space.
  24533. */
  24534. function lightViewPosition( light ) {
  24535. const data = getLightData( light );
  24536. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24537. self.value = self.value || new Vector3();
  24538. self.value.setFromMatrixPosition( light.matrixWorld );
  24539. self.value.applyMatrix4( camera.matrixWorldInverse );
  24540. } ) );
  24541. }
  24542. /**
  24543. * TSL function for getting the light target direction for the given light.
  24544. *
  24545. * @function
  24546. * @param {Light} light -The light source.
  24547. * @returns {Node<vec3>} The light's target direction.
  24548. */
  24549. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24550. /** @module LightsNode **/
  24551. const sortLights = ( lights ) => {
  24552. return lights.sort( ( a, b ) => a.id - b.id );
  24553. };
  24554. const getLightNodeById = ( id, lightNodes ) => {
  24555. for ( const lightNode of lightNodes ) {
  24556. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24557. return lightNode;
  24558. }
  24559. }
  24560. return null;
  24561. };
  24562. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24563. /**
  24564. * This node represents the scene's lighting and manages the lighting model's life cycle
  24565. * for the current build 3D object. It is responsible for computing the total outgoing
  24566. * light in a given lighting context.
  24567. *
  24568. * @augments Node
  24569. */
  24570. class LightsNode extends Node {
  24571. static get type() {
  24572. return 'LightsNode';
  24573. }
  24574. /**
  24575. * Constructs a new lights node.
  24576. */
  24577. constructor() {
  24578. super( 'vec3' );
  24579. /**
  24580. * A node representing the total diffuse light.
  24581. *
  24582. * @type {Node<vec3>}
  24583. */
  24584. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24585. /**
  24586. * A node representing the total specular light.
  24587. *
  24588. * @type {Node<vec3>}
  24589. */
  24590. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24591. /**
  24592. * A node representing the outgoing light.
  24593. *
  24594. * @type {Node<vec3>}
  24595. */
  24596. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24597. /**
  24598. * An array representing the lights in the scene.
  24599. *
  24600. * @private
  24601. * @type {Array<Light>}
  24602. */
  24603. this._lights = [];
  24604. /**
  24605. * For each light in the scene, this node will create a
  24606. * corresponding light node.
  24607. *
  24608. * @private
  24609. * @type {Array<LightingNode>?}
  24610. * @default null
  24611. */
  24612. this._lightNodes = null;
  24613. /**
  24614. * A hash for identifying the current light nodes setup.
  24615. *
  24616. * @private
  24617. * @type {String?}
  24618. * @default null
  24619. */
  24620. this._lightNodesHash = null;
  24621. /**
  24622. * `LightsNode` sets this property to `true` by default.
  24623. *
  24624. * @type {Boolean}
  24625. * @default true
  24626. */
  24627. this.global = true;
  24628. }
  24629. /**
  24630. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24631. * light IDs into the cache key.
  24632. *
  24633. * @return {Number} The custom cache key.
  24634. */
  24635. customCacheKey() {
  24636. const lightIDs = [];
  24637. const lights = this._lights;
  24638. for ( let i = 0; i < lights.length; i ++ ) {
  24639. lightIDs.push( lights[ i ].id );
  24640. }
  24641. return hashArray( lightIDs );
  24642. }
  24643. /**
  24644. * Computes a hash value for identifying the current light nodes setup.
  24645. *
  24646. * @param {NodeBuilder} builder - A reference to the current node builder.
  24647. * @return {String} The computed hash.
  24648. */
  24649. getHash( builder ) {
  24650. if ( this._lightNodesHash === null ) {
  24651. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24652. const hash = [];
  24653. for ( const lightNode of this._lightNodes ) {
  24654. hash.push( lightNode.getSelf().getHash() );
  24655. }
  24656. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24657. }
  24658. return this._lightNodesHash;
  24659. }
  24660. analyze( builder ) {
  24661. const properties = builder.getDataFromNode( this );
  24662. for ( const node of properties.nodes ) {
  24663. node.build( builder );
  24664. }
  24665. }
  24666. /**
  24667. * Creates lighting nodes for each scene light. This makes it possible to further
  24668. * process lights in the node system.
  24669. *
  24670. * @param {NodeBuilder} builder - A reference to the current node builder.
  24671. */
  24672. setupLightsNode( builder ) {
  24673. const lightNodes = [];
  24674. const previousLightNodes = this._lightNodes;
  24675. const lights = sortLights( this._lights );
  24676. const nodeLibrary = builder.renderer.library;
  24677. for ( const light of lights ) {
  24678. if ( light.isNode ) {
  24679. lightNodes.push( nodeObject( light ) );
  24680. } else {
  24681. let lightNode = null;
  24682. if ( previousLightNodes !== null ) {
  24683. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24684. }
  24685. if ( lightNode === null ) {
  24686. // find the corresponding node type for a given light
  24687. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24688. if ( lightNodeClass === null ) {
  24689. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24690. continue;
  24691. }
  24692. let lightNode = null;
  24693. if ( ! _lightsNodeRef.has( light ) ) {
  24694. lightNode = nodeObject( new lightNodeClass( light ) );
  24695. _lightsNodeRef.set( light, lightNode );
  24696. } else {
  24697. lightNode = _lightsNodeRef.get( light );
  24698. }
  24699. lightNodes.push( lightNode );
  24700. }
  24701. }
  24702. }
  24703. this._lightNodes = lightNodes;
  24704. }
  24705. /**
  24706. * Setups the internal lights by building all respective
  24707. * light nodes.
  24708. *
  24709. * @param {NodeBuilder} builder - A reference to the current node builder.
  24710. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24711. */
  24712. setupLights( builder, lightNodes ) {
  24713. for ( const lightNode of lightNodes ) {
  24714. lightNode.build( builder );
  24715. }
  24716. }
  24717. /**
  24718. * The implementation makes sure that for each light in the scene
  24719. * there is a corresponding light node. By building the light nodes
  24720. * and evaluating the lighting model the outgoing light is computed.
  24721. *
  24722. * @param {NodeBuilder} builder - A reference to the current node builder.
  24723. * @return {Node<vec3>} A node representing the outgoing light.
  24724. */
  24725. setup( builder ) {
  24726. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24727. const context = builder.context;
  24728. const lightingModel = context.lightingModel;
  24729. let outgoingLightNode = this.outgoingLightNode;
  24730. if ( lightingModel ) {
  24731. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24732. context.outgoingLight = outgoingLightNode;
  24733. const stack = builder.addStack();
  24734. //
  24735. const properties = builder.getDataFromNode( this );
  24736. properties.nodes = stack.nodes;
  24737. //
  24738. lightingModel.start( context, stack, builder );
  24739. // lights
  24740. this.setupLights( builder, _lightNodes );
  24741. //
  24742. lightingModel.indirect( context, stack, builder );
  24743. //
  24744. const { backdrop, backdropAlpha } = context;
  24745. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24746. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24747. if ( backdrop !== null ) {
  24748. if ( backdropAlpha !== null ) {
  24749. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24750. } else {
  24751. totalDiffuse = vec3( backdrop );
  24752. }
  24753. context.material.transparent = true;
  24754. }
  24755. totalDiffuseNode.assign( totalDiffuse );
  24756. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24757. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24758. //
  24759. lightingModel.finish( context, stack, builder );
  24760. //
  24761. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24762. }
  24763. return outgoingLightNode;
  24764. }
  24765. /**
  24766. * Configures this node with an array of lights.
  24767. *
  24768. * @param {Array<Light>} lights - An array of lights.
  24769. * @return {LightsNode} A reference to this node.
  24770. */
  24771. setLights( lights ) {
  24772. this._lights = lights;
  24773. this._lightNodes = null;
  24774. this._lightNodesHash = null;
  24775. return this;
  24776. }
  24777. /**
  24778. * Returns an array of the scene's lights.
  24779. *
  24780. * @return {Array<Light>} The scene's lights.
  24781. */
  24782. getLights() {
  24783. return this._lights;
  24784. }
  24785. /**
  24786. * Whether the scene has lights or not.
  24787. *
  24788. * @type {Boolean}
  24789. */
  24790. get hasLights() {
  24791. return this._lights.length > 0;
  24792. }
  24793. }
  24794. /**
  24795. * TSL function for creating an instance of `LightsNode` and configuring
  24796. * it with the given array of lights.
  24797. *
  24798. * @function
  24799. * @param {Array<Light>} lights - An array of lights.
  24800. * @return {LightsNode} The created lights node.
  24801. */
  24802. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24803. /** @module ShadowBaseNode **/
  24804. /**
  24805. * Base class for all shadow nodes.
  24806. *
  24807. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24808. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24809. * their requirements.
  24810. *
  24811. * @augments Node
  24812. */
  24813. class ShadowBaseNode extends Node {
  24814. static get type() {
  24815. return 'ShadowBaseNode';
  24816. }
  24817. /**
  24818. * Constructs a new shadow base node.
  24819. *
  24820. * @param {Light} light - The shadow casting light.
  24821. */
  24822. constructor( light ) {
  24823. super();
  24824. /**
  24825. * The shadow casting light.
  24826. *
  24827. * @type {Light}
  24828. */
  24829. this.light = light;
  24830. /**
  24831. * Overwritten since shadows are updated by default per render.
  24832. *
  24833. * @type {String}
  24834. * @default 'render'
  24835. */
  24836. this.updateBeforeType = NodeUpdateType.RENDER;
  24837. /**
  24838. * This flag can be used for type testing.
  24839. *
  24840. * @type {Boolean}
  24841. * @readonly
  24842. * @default true
  24843. */
  24844. this.isShadowBaseNode = true;
  24845. }
  24846. /**
  24847. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24848. *
  24849. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24850. */
  24851. setupShadowPosition( { material } ) {
  24852. // Use assign inside an Fn()
  24853. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24854. }
  24855. /**
  24856. * Can be called when the shadow isn't required anymore. That can happen when
  24857. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24858. * to `false`.
  24859. */
  24860. dispose() {
  24861. this.updateBeforeType = NodeUpdateType.NONE;
  24862. }
  24863. }
  24864. /**
  24865. * TSL object that represents the vertex position in world space during the shadow pass.
  24866. *
  24867. * @type {Node<vec3>}
  24868. */
  24869. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24870. /** @module RendererUtils **/
  24871. /**
  24872. * Saves the state of the given renderer and stores it into the given state object.
  24873. *
  24874. * If not state object is provided, the function creates one.
  24875. *
  24876. * @function
  24877. * @param {Renderer} renderer - The renderer.
  24878. * @param {Object} [state={}] - The state.
  24879. * @return {Object} The state.
  24880. */
  24881. function saveRendererState( renderer, state = {} ) {
  24882. state.toneMapping = renderer.toneMapping;
  24883. state.toneMappingExposure = renderer.toneMappingExposure;
  24884. state.outputColorSpace = renderer.outputColorSpace;
  24885. state.renderTarget = renderer.getRenderTarget();
  24886. state.activeCubeFace = renderer.getActiveCubeFace();
  24887. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24888. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24889. state.pixelRatio = renderer.getPixelRatio();
  24890. state.mrt = renderer.getMRT();
  24891. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24892. state.clearAlpha = renderer.getClearAlpha();
  24893. state.autoClear = renderer.autoClear;
  24894. state.scissorTest = renderer.getScissorTest();
  24895. return state;
  24896. }
  24897. /**
  24898. * Saves the state of the given renderer and stores it into the given state object.
  24899. * Besides, the function also resets the state of the renderer to its default values.
  24900. *
  24901. * If not state object is provided, the function creates one.
  24902. *
  24903. * @function
  24904. * @param {Renderer} renderer - The renderer.
  24905. * @param {Object} [state={}] - The state.
  24906. * @return {Object} The state.
  24907. */
  24908. function resetRendererState( renderer, state ) {
  24909. state = saveRendererState( renderer, state );
  24910. renderer.setMRT( null );
  24911. renderer.setRenderObjectFunction( null );
  24912. renderer.setClearColor( 0x000000, 1 );
  24913. renderer.autoClear = true;
  24914. return state;
  24915. }
  24916. /**
  24917. * Restores the state of the given renderer from the given state object.
  24918. *
  24919. * @function
  24920. * @param {Renderer} renderer - The renderer.
  24921. * @param {Object} state - The state to restore.
  24922. */
  24923. function restoreRendererState( renderer, state ) {
  24924. renderer.toneMapping = state.toneMapping;
  24925. renderer.toneMappingExposure = state.toneMappingExposure;
  24926. renderer.outputColorSpace = state.outputColorSpace;
  24927. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24928. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24929. renderer.setPixelRatio( state.pixelRatio );
  24930. renderer.setMRT( state.mrt );
  24931. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24932. renderer.autoClear = state.autoClear;
  24933. renderer.setScissorTest( state.scissorTest );
  24934. }
  24935. /**
  24936. * Saves the state of the given scene and stores it into the given state object.
  24937. *
  24938. * If not state object is provided, the function creates one.
  24939. *
  24940. * @function
  24941. * @param {Scene} scene - The scene.
  24942. * @param {Object} [state={}] - The state.
  24943. * @return {Object} The state.
  24944. */
  24945. function saveSceneState( scene, state = {} ) {
  24946. state.background = scene.background;
  24947. state.backgroundNode = scene.backgroundNode;
  24948. state.overrideMaterial = scene.overrideMaterial;
  24949. return state;
  24950. }
  24951. /**
  24952. * Saves the state of the given scene and stores it into the given state object.
  24953. * Besides, the function also resets the state of the scene to its default values.
  24954. *
  24955. * If not state object is provided, the function creates one.
  24956. *
  24957. * @function
  24958. * @param {Scene} scene - The scene.
  24959. * @param {Object} [state={}] - The state.
  24960. * @return {Object} The state.
  24961. */
  24962. function resetSceneState( scene, state ) {
  24963. state = saveSceneState( scene, state );
  24964. scene.background = null;
  24965. scene.backgroundNode = null;
  24966. scene.overrideMaterial = null;
  24967. return state;
  24968. }
  24969. /**
  24970. * Restores the state of the given scene from the given state object.
  24971. *
  24972. * @function
  24973. * @param {Scene} scene - The scene.
  24974. * @param {Object} state - The state to restore.
  24975. */
  24976. function restoreSceneState( scene, state ) {
  24977. scene.background = state.background;
  24978. scene.backgroundNode = state.backgroundNode;
  24979. scene.overrideMaterial = state.overrideMaterial;
  24980. }
  24981. /**
  24982. * Saves the state of the given renderer and scene and stores it into the given state object.
  24983. *
  24984. * If not state object is provided, the function creates one.
  24985. *
  24986. * @function
  24987. * @param {Renderer} renderer - The renderer.
  24988. * @param {Scene} scene - The scene.
  24989. * @param {Object} [state={}] - The state.
  24990. * @return {Object} The state.
  24991. */
  24992. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24993. state = saveRendererState( renderer, state );
  24994. state = saveSceneState( scene, state );
  24995. return state;
  24996. }
  24997. /**
  24998. * Saves the state of the given renderer and scene and stores it into the given state object.
  24999. * Besides, the function also resets the state of the renderer and scene to its default values.
  25000. *
  25001. * If not state object is provided, the function creates one.
  25002. *
  25003. * @function
  25004. * @param {Renderer} renderer - The renderer.
  25005. * @param {Scene} scene - The scene.
  25006. * @param {Object} [state={}] - The state.
  25007. * @return {Object} The state.
  25008. */
  25009. function resetRendererAndSceneState( renderer, scene, state ) {
  25010. state = resetRendererState( renderer, state );
  25011. state = resetSceneState( scene, state );
  25012. return state;
  25013. }
  25014. /**
  25015. * Restores the state of the given renderer and scene from the given state object.
  25016. *
  25017. * @function
  25018. * @param {Renderer} renderer - The renderer.
  25019. * @param {Scene} scene - The scene.
  25020. * @param {Object} state - The state to restore.
  25021. */
  25022. function restoreRendererAndSceneState( renderer, scene, state ) {
  25023. restoreRendererState( renderer, state );
  25024. restoreSceneState( scene, state );
  25025. }
  25026. var RendererUtils = /*#__PURE__*/Object.freeze({
  25027. __proto__: null,
  25028. resetRendererAndSceneState: resetRendererAndSceneState,
  25029. resetRendererState: resetRendererState,
  25030. resetSceneState: resetSceneState,
  25031. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25032. restoreRendererState: restoreRendererState,
  25033. restoreSceneState: restoreSceneState,
  25034. saveRendererAndSceneState: saveRendererAndSceneState,
  25035. saveRendererState: saveRendererState,
  25036. saveSceneState: saveSceneState
  25037. });
  25038. /** @module ShadowNode **/
  25039. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25040. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25041. let dist = positionWorld.sub( position ).length();
  25042. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25043. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25044. return dist;
  25045. } );
  25046. const linearShadowDistance = ( light ) => {
  25047. const camera = light.shadow.camera;
  25048. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25049. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25050. const referencePosition = objectPosition( light );
  25051. return linearDistance( referencePosition, nearDistance, farDistance );
  25052. };
  25053. const getShadowMaterial = ( light ) => {
  25054. let material = shadowMaterialLib.get( light );
  25055. if ( material === undefined ) {
  25056. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25057. material = new NodeMaterial();
  25058. material.colorNode = vec4( 0, 0, 0, 1 );
  25059. material.depthNode = depthNode;
  25060. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25061. material.name = 'ShadowMaterial';
  25062. material.fog = false;
  25063. shadowMaterialLib.set( light, material );
  25064. }
  25065. return material;
  25066. };
  25067. /**
  25068. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25069. * with a binary `[0,1]` result.
  25070. *
  25071. * @method
  25072. * @param {Object} inputs - The input parameter object.
  25073. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25074. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25075. * @return {Node<float>} The filtering result.
  25076. */
  25077. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25078. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25079. } );
  25080. /**
  25081. * A shadow filtering function performing PCF filtering.
  25082. *
  25083. * @method
  25084. * @param {Object} inputs - The input parameter object.
  25085. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25086. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25087. * @param {LightShadow} inputs.shadow - The light shadow.
  25088. * @return {Node<float>} The filtering result.
  25089. */
  25090. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25091. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25092. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25093. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25094. const texelSize = vec2( 1 ).div( mapSize );
  25095. const dx0 = texelSize.x.negate().mul( radius );
  25096. const dy0 = texelSize.y.negate().mul( radius );
  25097. const dx1 = texelSize.x.mul( radius );
  25098. const dy1 = texelSize.y.mul( radius );
  25099. const dx2 = dx0.div( 2 );
  25100. const dy2 = dy0.div( 2 );
  25101. const dx3 = dx1.div( 2 );
  25102. const dy3 = dy1.div( 2 );
  25103. return add(
  25104. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25105. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25106. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25107. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25108. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25109. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25110. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25111. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25112. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25113. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25114. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25115. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25116. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25117. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25118. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25119. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25120. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25121. ).mul( 1 / 17 );
  25122. } );
  25123. /**
  25124. * A shadow filtering function performing PCF soft filtering.
  25125. *
  25126. * @method
  25127. * @param {Object} inputs - The input parameter object.
  25128. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25129. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25130. * @param {LightShadow} inputs.shadow - The light shadow.
  25131. * @return {Node<float>} The filtering result.
  25132. */
  25133. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25134. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25135. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25136. const texelSize = vec2( 1 ).div( mapSize );
  25137. const dx = texelSize.x;
  25138. const dy = texelSize.y;
  25139. const uv = shadowCoord.xy;
  25140. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25141. uv.subAssign( f.mul( texelSize ) );
  25142. return add(
  25143. depthCompare( uv, shadowCoord.z ),
  25144. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25145. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25146. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25147. mix(
  25148. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25149. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25150. f.x
  25151. ),
  25152. mix(
  25153. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25154. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25155. f.x
  25156. ),
  25157. mix(
  25158. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25159. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25160. f.y
  25161. ),
  25162. mix(
  25163. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25164. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25165. f.y
  25166. ),
  25167. mix(
  25168. mix(
  25169. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25170. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25171. f.x
  25172. ),
  25173. mix(
  25174. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25175. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25176. f.x
  25177. ),
  25178. f.y
  25179. )
  25180. ).mul( 1 / 9 );
  25181. } );
  25182. /**
  25183. * A shadow filtering function performing VSM filtering.
  25184. *
  25185. * @method
  25186. * @param {Object} inputs - The input parameter object.
  25187. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25188. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25189. * @return {Node<float>} The filtering result.
  25190. */
  25191. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25192. const occlusion = float( 1 ).toVar();
  25193. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25194. const hardShadow = step( shadowCoord.z, distribution.x );
  25195. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25196. const distance = shadowCoord.z.sub( distribution.x );
  25197. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25198. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25199. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25200. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25201. } );
  25202. return occlusion;
  25203. } );
  25204. /**
  25205. * Represents the shader code for the first VSM render pass.
  25206. *
  25207. * @method
  25208. * @param {Object} inputs - The input parameter object.
  25209. * @param {Node<float>} inputs.samples - The number of samples
  25210. * @param {Node<float>} inputs.radius - The radius.
  25211. * @param {Node<float>} inputs.size - The size.
  25212. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25213. * @return {Node<vec2>} The VSM output.
  25214. */
  25215. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25216. const mean = float( 0 ).toVar();
  25217. const squaredMean = float( 0 ).toVar();
  25218. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25219. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25220. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25221. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25222. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25223. mean.addAssign( depth );
  25224. squaredMean.addAssign( depth.mul( depth ) );
  25225. } );
  25226. mean.divAssign( samples );
  25227. squaredMean.divAssign( samples );
  25228. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25229. return vec2( mean, std_dev );
  25230. } );
  25231. /**
  25232. * Represents the shader code for the second VSM render pass.
  25233. *
  25234. * @method
  25235. * @param {Object} inputs - The input parameter object.
  25236. * @param {Node<float>} inputs.samples - The number of samples
  25237. * @param {Node<float>} inputs.radius - The radius.
  25238. * @param {Node<float>} inputs.size - The size.
  25239. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25240. * @return {Node<vec2>} The VSM output.
  25241. */
  25242. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25243. const mean = float( 0 ).toVar();
  25244. const squaredMean = float( 0 ).toVar();
  25245. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25246. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25247. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25248. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25249. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25250. mean.addAssign( distribution.x );
  25251. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25252. } );
  25253. mean.divAssign( samples );
  25254. squaredMean.divAssign( samples );
  25255. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25256. return vec2( mean, std_dev );
  25257. } );
  25258. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25259. //
  25260. let _rendererState;
  25261. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25262. /**
  25263. * Represents the default shadow implementation for lighting nodes.
  25264. *
  25265. * @augments module:ShadowBaseNode~ShadowBaseNode
  25266. */
  25267. class ShadowNode extends ShadowBaseNode {
  25268. static get type() {
  25269. return 'ShadowNode';
  25270. }
  25271. /**
  25272. * Constructs a new shadow node.
  25273. *
  25274. * @param {Light} light - The shadow casting light.
  25275. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25276. */
  25277. constructor( light, shadow = null ) {
  25278. super( light );
  25279. /**
  25280. * The light shadow which defines the properties light's
  25281. * shadow.
  25282. *
  25283. * @type {LightShadow?}
  25284. * @default null
  25285. */
  25286. this.shadow = shadow || light.shadow;
  25287. /**
  25288. * A reference to the shadow map which is a render target.
  25289. *
  25290. * @type {RenderTarget?}
  25291. * @default null
  25292. */
  25293. this.shadowMap = null;
  25294. /**
  25295. * Only relevant for VSM shadows. Render target for the
  25296. * first VSM render pass.
  25297. *
  25298. * @type {RenderTarget?}
  25299. * @default null
  25300. */
  25301. this.vsmShadowMapVertical = null;
  25302. /**
  25303. * Only relevant for VSM shadows. Render target for the
  25304. * second VSM render pass.
  25305. *
  25306. * @type {RenderTarget?}
  25307. * @default null
  25308. */
  25309. this.vsmShadowMapHorizontal = null;
  25310. /**
  25311. * Only relevant for VSM shadows. Node material which
  25312. * is used to render the first VSM pass.
  25313. *
  25314. * @type {NodeMaterial?}
  25315. * @default null
  25316. */
  25317. this.vsmMaterialVertical = null;
  25318. /**
  25319. * Only relevant for VSM shadows. Node material which
  25320. * is used to render the second VSM pass.
  25321. *
  25322. * @type {NodeMaterial?}
  25323. * @default null
  25324. */
  25325. this.vsmMaterialHorizontal = null;
  25326. /**
  25327. * A reference to the output node which defines the
  25328. * final result of this shadow node.
  25329. *
  25330. * @type {Node?}
  25331. * @private
  25332. * @default null
  25333. */
  25334. this._node = null;
  25335. /**
  25336. * This flag can be used for type testing.
  25337. *
  25338. * @type {Boolean}
  25339. * @readonly
  25340. * @default true
  25341. */
  25342. this.isShadowNode = true;
  25343. }
  25344. /**
  25345. * Setups the shadow filtering.
  25346. *
  25347. * @param {NodeBuilder} builder - A reference to the current node builder.
  25348. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25349. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25350. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25351. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25352. * @param {LightShadow} inputs.shadow - The light shadow.
  25353. * @return {Node<float>} The result node of the shadow filtering.
  25354. */
  25355. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25356. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25357. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25358. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25359. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25360. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25361. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25362. return frustumTest.select( shadowNode, float( 1 ) );
  25363. }
  25364. /**
  25365. * Setups the shadow coordinates.
  25366. *
  25367. * @param {NodeBuilder} builder - A reference to the current node builder.
  25368. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25369. * @return {Node<vec3>} The shadow coordinates.
  25370. */
  25371. setupShadowCoord( builder, shadowPosition ) {
  25372. const { shadow } = this;
  25373. const { renderer } = builder;
  25374. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25375. let shadowCoord = shadowPosition;
  25376. let coordZ;
  25377. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25378. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25379. coordZ = shadowCoord.z;
  25380. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25381. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25382. }
  25383. } else {
  25384. const w = shadowCoord.w;
  25385. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25386. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25387. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25388. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25389. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25390. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25391. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25392. }
  25393. shadowCoord = vec3(
  25394. shadowCoord.x,
  25395. shadowCoord.y.oneMinus(), // follow webgpu standards
  25396. coordZ.add( bias )
  25397. );
  25398. return shadowCoord;
  25399. }
  25400. /**
  25401. * Returns the shadow filtering function for the given shadow type.
  25402. *
  25403. * @param {Number} type - The shadow type.
  25404. * @return {Function} The filtering function.
  25405. */
  25406. getShadowFilterFn( type ) {
  25407. return _shadowFilterLib[ type ];
  25408. }
  25409. /**
  25410. * Setups the shadow output node.
  25411. *
  25412. * @param {NodeBuilder} builder - A reference to the current node builder.
  25413. * @return {Node<vec3>} The shadow output node.
  25414. */
  25415. setupShadow( builder ) {
  25416. const { renderer } = builder;
  25417. const { light, shadow } = this;
  25418. const shadowMapType = renderer.shadowMap.type;
  25419. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25420. depthTexture.compareFunction = LessCompare;
  25421. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25422. shadowMap.depthTexture = depthTexture;
  25423. shadow.camera.updateProjectionMatrix();
  25424. // VSM
  25425. if ( shadowMapType === VSMShadowMap ) {
  25426. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25427. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25428. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25429. const shadowPassVertical = texture( depthTexture );
  25430. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25431. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25432. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25433. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25434. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25435. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25436. material.name = 'VSMVertical';
  25437. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25438. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25439. material.name = 'VSMHorizontal';
  25440. }
  25441. //
  25442. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25443. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25444. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25445. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25446. //
  25447. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25448. if ( filterFn === null ) {
  25449. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25450. }
  25451. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25452. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25453. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25454. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25455. this.shadowMap = shadowMap;
  25456. this.shadow.map = shadowMap;
  25457. return shadowOutput;
  25458. }
  25459. /**
  25460. * The implementation performs the setup of the output node. An output is only
  25461. * produces if shadow mapping is globally enabled in the renderer.
  25462. *
  25463. * @param {NodeBuilder} builder - A reference to the current node builder.
  25464. * @return {ShaderCallNodeInternal} The output node.
  25465. */
  25466. setup( builder ) {
  25467. if ( builder.renderer.shadowMap.enabled === false ) return;
  25468. return Fn( () => {
  25469. let node = this._node;
  25470. this.setupShadowPosition( builder );
  25471. if ( node === null ) {
  25472. this._node = node = this.setupShadow( builder );
  25473. }
  25474. if ( builder.material.shadowNode ) { // @deprecated, r171
  25475. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25476. }
  25477. if ( builder.material.receivedShadowNode ) {
  25478. node = builder.material.receivedShadowNode( node );
  25479. }
  25480. return node;
  25481. } )();
  25482. }
  25483. /**
  25484. * Renders the shadow. The logic of this function could be included
  25485. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25486. * nodes might require a custom shadow map rendering. By having a
  25487. * dedicated method, it's easier to overwrite the default behavior.
  25488. *
  25489. * @param {NodeFrame} frame - A reference to the current node frame.
  25490. */
  25491. renderShadow( frame ) {
  25492. const { shadow, shadowMap, light } = this;
  25493. const { renderer, scene } = frame;
  25494. shadow.updateMatrices( light );
  25495. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25496. renderer.render( scene, shadow.camera );
  25497. }
  25498. /**
  25499. * Updates the shadow.
  25500. *
  25501. * @param {NodeFrame} frame - A reference to the current node frame.
  25502. */
  25503. updateShadow( frame ) {
  25504. const { shadowMap, light, shadow } = this;
  25505. const { renderer, scene, camera } = frame;
  25506. const shadowType = renderer.shadowMap.type;
  25507. const depthVersion = shadowMap.depthTexture.version;
  25508. this._depthVersionCached = depthVersion;
  25509. shadow.camera.layers.mask = camera.layers.mask;
  25510. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25511. const currentMRT = renderer.getMRT();
  25512. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25513. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25514. scene.overrideMaterial = getShadowMaterial( light );
  25515. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25516. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25517. if ( useVelocity ) {
  25518. getDataFromObject( object ).useVelocity = true;
  25519. }
  25520. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25521. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25522. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25523. }
  25524. } );
  25525. renderer.setRenderTarget( shadowMap );
  25526. this.renderShadow( frame );
  25527. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25528. // vsm blur pass
  25529. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25530. this.vsmPass( renderer );
  25531. }
  25532. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25533. }
  25534. /**
  25535. * For VSM additional render passes are required.
  25536. *
  25537. * @param {Renderer} renderer - A reference to the current renderer.
  25538. */
  25539. vsmPass( renderer ) {
  25540. const { shadow } = this;
  25541. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25542. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25543. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25544. _quadMesh.material = this.vsmMaterialVertical;
  25545. _quadMesh.render( renderer );
  25546. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25547. _quadMesh.material = this.vsmMaterialHorizontal;
  25548. _quadMesh.render( renderer );
  25549. }
  25550. /**
  25551. * Frees the internal resources of this shadow node.
  25552. */
  25553. dispose() {
  25554. this.shadowMap.dispose();
  25555. this.shadowMap = null;
  25556. if ( this.vsmShadowMapVertical !== null ) {
  25557. this.vsmShadowMapVertical.dispose();
  25558. this.vsmShadowMapVertical = null;
  25559. this.vsmMaterialVertical.dispose();
  25560. this.vsmMaterialVertical = null;
  25561. }
  25562. if ( this.vsmShadowMapHorizontal !== null ) {
  25563. this.vsmShadowMapHorizontal.dispose();
  25564. this.vsmShadowMapHorizontal = null;
  25565. this.vsmMaterialHorizontal.dispose();
  25566. this.vsmMaterialHorizontal = null;
  25567. }
  25568. super.dispose();
  25569. }
  25570. /**
  25571. * The implementation performs the update of the shadow map if necessary.
  25572. *
  25573. * @param {NodeFrame} frame - A reference to the current node frame.
  25574. */
  25575. updateBefore( frame ) {
  25576. const { shadow } = this;
  25577. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25578. if ( needsUpdate ) {
  25579. this.updateShadow( frame );
  25580. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25581. shadow.needsUpdate = false;
  25582. }
  25583. }
  25584. }
  25585. }
  25586. /**
  25587. * TSL function for creating an instance of `ShadowNode`.
  25588. *
  25589. * @function
  25590. * @param {Light} light - The shadow casting light.
  25591. * @param {LightShadow} shadow - The light shadow.
  25592. * @return {ShadowNode} The created shadow node.
  25593. */
  25594. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25595. /**
  25596. * Base class for analytic light nodes.
  25597. *
  25598. * @augments LightingNode
  25599. */
  25600. class AnalyticLightNode extends LightingNode {
  25601. static get type() {
  25602. return 'AnalyticLightNode';
  25603. }
  25604. /**
  25605. * Constructs a new analytic light node.
  25606. *
  25607. * @param {Light?} [light=null] - The light source.
  25608. */
  25609. constructor( light = null ) {
  25610. super();
  25611. /**
  25612. * The light source.
  25613. *
  25614. * @type {Light?}
  25615. * @default null
  25616. */
  25617. this.light = light;
  25618. /**
  25619. * The light's color value.
  25620. *
  25621. * @type {Color}
  25622. */
  25623. this.color = new Color();
  25624. /**
  25625. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25626. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25627. *
  25628. * @type {Node}
  25629. */
  25630. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25631. /**
  25632. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25633. * The final color node is represented by a different node when using shadows.
  25634. *
  25635. * @type {Node?}
  25636. * @default null
  25637. */
  25638. this.baseColorNode = null;
  25639. /**
  25640. * Represents the light's shadow.
  25641. *
  25642. * @type {ShadowNode?}
  25643. * @default null
  25644. */
  25645. this.shadowNode = null;
  25646. /**
  25647. * Represents the light's shadow color.
  25648. *
  25649. * @type {Node?}
  25650. * @default null
  25651. */
  25652. this.shadowColorNode = null;
  25653. /**
  25654. * This flag can be used for type testing.
  25655. *
  25656. * @type {Boolean}
  25657. * @readonly
  25658. * @default true
  25659. */
  25660. this.isAnalyticLightNode = true;
  25661. /**
  25662. * Overwritten since analytic light nodes are updated
  25663. * once per frame.
  25664. *
  25665. * @type {String}
  25666. * @default 'frame'
  25667. */
  25668. this.updateType = NodeUpdateType.FRAME;
  25669. }
  25670. /**
  25671. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25672. * `light.id` and `light.castShadow` into the cache key.
  25673. *
  25674. * @return {Number} The custom cache key.
  25675. */
  25676. customCacheKey() {
  25677. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25678. }
  25679. getHash() {
  25680. return this.light.uuid;
  25681. }
  25682. /**
  25683. * Setups the shadow node for this light. The method exists so concrete light classes
  25684. * can setup different types of shadow nodes.
  25685. *
  25686. * @return {ShadowNode} The created shadow node.
  25687. */
  25688. setupShadowNode() {
  25689. return shadow( this.light );
  25690. }
  25691. /**
  25692. * Setups the shadow for this light. This method is only executed if the light
  25693. * cast shadows and the current build object receives shadows. It incorporates
  25694. * shadows into the lighting computation.
  25695. *
  25696. * @param {NodeBuilder} builder - The current node builder.
  25697. */
  25698. setupShadow( builder ) {
  25699. const { renderer } = builder;
  25700. if ( renderer.shadowMap.enabled === false ) return;
  25701. let shadowColorNode = this.shadowColorNode;
  25702. if ( shadowColorNode === null ) {
  25703. const customShadowNode = this.light.shadow.shadowNode;
  25704. let shadowNode;
  25705. if ( customShadowNode !== undefined ) {
  25706. shadowNode = nodeObject( customShadowNode );
  25707. } else {
  25708. shadowNode = this.setupShadowNode( builder );
  25709. }
  25710. this.shadowNode = shadowNode;
  25711. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25712. this.baseColorNode = this.colorNode;
  25713. }
  25714. //
  25715. this.colorNode = shadowColorNode;
  25716. }
  25717. /**
  25718. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25719. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25720. * invocate the respective interface methods.
  25721. *
  25722. * @param {NodeBuilder} builder - The current node builder.
  25723. */
  25724. setup( builder ) {
  25725. this.colorNode = this.baseColorNode || this.colorNode;
  25726. if ( this.light.castShadow ) {
  25727. if ( builder.object.receiveShadow ) {
  25728. this.setupShadow( builder );
  25729. }
  25730. } else if ( this.shadowNode !== null ) {
  25731. this.shadowNode.dispose();
  25732. this.shadowNode = null;
  25733. this.shadowColorNode = null;
  25734. }
  25735. }
  25736. /**
  25737. * The update method is used to update light uniforms per frame.
  25738. * Potentially overwritten in concrete light nodes to update light
  25739. * specific uniforms.
  25740. *
  25741. * @param {NodeFrame} frame - A reference to the current node frame.
  25742. */
  25743. update( /*frame*/ ) {
  25744. const { light } = this;
  25745. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25746. }
  25747. }
  25748. /** @module LightUtils **/
  25749. /**
  25750. * Represents a `discard` shader operation in TSL.
  25751. *
  25752. * @method
  25753. * @param {Object} inputs - The input parameter object.
  25754. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25755. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25756. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25757. * @return {Node<float>} The distance falloff.
  25758. */
  25759. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25760. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25761. // based upon Frostbite 3 Moving to Physically-based Rendering
  25762. // page 32, equation 26: E[window1]
  25763. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25764. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25765. return cutoffDistance.greaterThan( 0 ).select(
  25766. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25767. distanceFalloff
  25768. );
  25769. } ); // validated
  25770. /** @module PointShadowNode **/
  25771. const _clearColor$2 = /*@__PURE__*/ new Color();
  25772. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25773. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25774. // 2D texture:
  25775. //
  25776. // xzXZ
  25777. // y Y
  25778. //
  25779. // Y - Positive y direction
  25780. // y - Negative y direction
  25781. // X - Positive x direction
  25782. // x - Negative x direction
  25783. // Z - Positive z direction
  25784. // z - Negative z direction
  25785. //
  25786. // Source and test bed:
  25787. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25788. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25789. const v = pos.toVar();
  25790. // Number of texels to avoid at the edge of each square
  25791. const absV = abs( v );
  25792. // Intersect unit cube
  25793. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25794. absV.mulAssign( scaleToCube );
  25795. // Apply scale to avoid seams
  25796. // two texels less per square (one texel will do for NEAREST)
  25797. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25798. // Unwrap
  25799. // space: -1 ... 1 range for each square
  25800. //
  25801. // #X## dim := ( 4 , 2 )
  25802. // # # center := ( 1 , 1 )
  25803. const planar = vec2( v.xy ).toVar();
  25804. const almostATexel = texelSizeY.mul( 1.5 );
  25805. const almostOne = almostATexel.oneMinus();
  25806. If( absV.z.greaterThanEqual( almostOne ), () => {
  25807. If( v.z.greaterThan( 0.0 ), () => {
  25808. planar.x.assign( sub( 4.0, v.x ) );
  25809. } );
  25810. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25811. const signX = sign( v.x );
  25812. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25813. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25814. const signY = sign( v.y );
  25815. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25816. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25817. } );
  25818. // Transform to UV space
  25819. // scale := 0.5 / dim
  25820. // translate := ( center + 0.5 ) / dim
  25821. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25822. } ).setLayout( {
  25823. name: 'cubeToUV',
  25824. type: 'vec2',
  25825. inputs: [
  25826. { name: 'pos', type: 'vec3' },
  25827. { name: 'texelSizeY', type: 'float' }
  25828. ]
  25829. } );
  25830. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25831. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25832. } );
  25833. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25834. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25835. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  25836. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25837. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25838. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25839. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25840. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25841. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25842. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25843. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25844. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25845. .mul( 1.0 / 9.0 );
  25846. } );
  25847. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25848. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25849. // the vector from the light to the world-space position of the fragment.
  25850. const lightToPosition = shadowCoord.xyz.toVar();
  25851. const lightToPositionLength = lightToPosition.length();
  25852. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25853. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25854. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25855. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25856. const result = float( 1.0 ).toVar();
  25857. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25858. // dp = normalized distance from light to fragment position
  25859. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25860. dp.addAssign( bias );
  25861. // bd3D = base direction 3D
  25862. const bd3D = lightToPosition.normalize();
  25863. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25864. // percentage-closer filtering
  25865. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25866. } );
  25867. return result;
  25868. } );
  25869. const _viewport = /*@__PURE__*/ new Vector4();
  25870. const _viewportSize = /*@__PURE__*/ new Vector2();
  25871. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25872. /**
  25873. * Represents the shadow implementation for point light nodes.
  25874. *
  25875. * @augments module:ShadowNode~ShadowNode
  25876. */
  25877. class PointShadowNode extends ShadowNode {
  25878. static get type() {
  25879. return 'PointShadowNode';
  25880. }
  25881. /**
  25882. * Constructs a new point shadow node.
  25883. *
  25884. * @param {PointLight} light - The shadow casting point light.
  25885. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25886. */
  25887. constructor( light, shadow = null ) {
  25888. super( light, shadow );
  25889. }
  25890. /**
  25891. * Overwrites the default implementation to return point light shadow specific
  25892. * filtering functions.
  25893. *
  25894. * @param {Number} type - The shadow type.
  25895. * @return {Function} The filtering function.
  25896. */
  25897. getShadowFilterFn( type ) {
  25898. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25899. }
  25900. /**
  25901. * Overwrites the default implementation so the unaltered shadow position is used.
  25902. *
  25903. * @param {NodeBuilder} builder - A reference to the current node builder.
  25904. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25905. * @return {Node<vec3>} The shadow coordinates.
  25906. */
  25907. setupShadowCoord( builder, shadowPosition ) {
  25908. return shadowPosition;
  25909. }
  25910. /**
  25911. * Overwrites the default implementation to only use point light specific
  25912. * shadow filter functions.
  25913. *
  25914. * @param {NodeBuilder} builder - A reference to the current node builder.
  25915. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25916. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25917. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25918. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25919. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25920. * @param {LightShadow} inputs.shadow - The light shadow.
  25921. * @return {Node<float>} The result node of the shadow filtering.
  25922. */
  25923. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25924. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25925. }
  25926. /**
  25927. * Overwrites the default implementation with point light specific
  25928. * rendering code.
  25929. *
  25930. * @param {NodeFrame} frame - A reference to the current node frame.
  25931. */
  25932. renderShadow( frame ) {
  25933. const { shadow, shadowMap, light } = this;
  25934. const { renderer, scene } = frame;
  25935. const shadowFrameExtents = shadow.getFrameExtents();
  25936. _shadowMapSize.copy( shadow.mapSize );
  25937. _shadowMapSize.multiply( shadowFrameExtents );
  25938. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25939. _viewportSize.copy( shadow.mapSize );
  25940. //
  25941. const previousAutoClear = renderer.autoClear;
  25942. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25943. const previousClearAlpha = renderer.getClearAlpha();
  25944. renderer.autoClear = false;
  25945. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25946. renderer.clear();
  25947. const viewportCount = shadow.getViewportCount();
  25948. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25949. const viewport = shadow.getViewport( vp );
  25950. const x = _viewportSize.x * viewport.x;
  25951. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25952. _viewport.set(
  25953. x,
  25954. y,
  25955. _viewportSize.x * viewport.z,
  25956. _viewportSize.y * viewport.w
  25957. );
  25958. shadowMap.viewport.copy( _viewport );
  25959. shadow.updateMatrices( light, vp );
  25960. renderer.render( scene, shadow.camera );
  25961. }
  25962. //
  25963. renderer.autoClear = previousAutoClear;
  25964. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25965. }
  25966. }
  25967. /**
  25968. * TSL function for creating an instance of `PointShadowNode`.
  25969. *
  25970. * @function
  25971. * @param {PointLight} light - The shadow casting point light.
  25972. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25973. * @return {PointShadowNode} The created point shadow node.
  25974. */
  25975. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25976. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25977. const lightingModel = builder.context.lightingModel;
  25978. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25979. const lightDirection = lVector.normalize();
  25980. const lightDistance = lVector.length();
  25981. const lightAttenuation = getDistanceAttenuation( {
  25982. lightDistance,
  25983. cutoffDistance,
  25984. decayExponent
  25985. } );
  25986. const lightColor = color.mul( lightAttenuation );
  25987. const reflectedLight = builder.context.reflectedLight;
  25988. lightingModel.direct( {
  25989. lightDirection,
  25990. lightColor,
  25991. reflectedLight
  25992. }, builder.stack, builder );
  25993. } );
  25994. /**
  25995. * Module for representing point lights as nodes.
  25996. *
  25997. * @augments AnalyticLightNode
  25998. */
  25999. class PointLightNode extends AnalyticLightNode {
  26000. static get type() {
  26001. return 'PointLightNode';
  26002. }
  26003. /**
  26004. * Constructs a new point light node.
  26005. *
  26006. * @param {PointLight?} [light=null] - The point light source.
  26007. */
  26008. constructor( light = null ) {
  26009. super( light );
  26010. /**
  26011. * Uniform node representing the cutoff distance.
  26012. *
  26013. * @type {UniformNode<float>}
  26014. */
  26015. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26016. /**
  26017. * Uniform node representing the decay exponent.
  26018. *
  26019. * @type {UniformNode<float>}
  26020. */
  26021. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26022. }
  26023. /**
  26024. * Overwritten to updated point light specific uniforms.
  26025. *
  26026. * @param {NodeFrame} frame - A reference to the current node frame.
  26027. */
  26028. update( frame ) {
  26029. const { light } = this;
  26030. super.update( frame );
  26031. this.cutoffDistanceNode.value = light.distance;
  26032. this.decayExponentNode.value = light.decay;
  26033. }
  26034. /**
  26035. * Overwritten to setup point light specific shadow.
  26036. *
  26037. * @return {PointShadowNode}
  26038. */
  26039. setupShadowNode() {
  26040. return pointShadow( this.light );
  26041. }
  26042. setup( builder ) {
  26043. super.setup( builder );
  26044. directPointLight( {
  26045. color: this.colorNode,
  26046. lightViewPosition: lightViewPosition( this.light ),
  26047. cutoffDistance: this.cutoffDistanceNode,
  26048. decayExponent: this.decayExponentNode
  26049. } ).append();
  26050. }
  26051. }
  26052. /** @module Procedural **/
  26053. /**
  26054. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26055. *
  26056. * @method
  26057. * @param {Node<vec2>} coord - The uv coordinates.
  26058. * @return {Node<float>} The result data.
  26059. */
  26060. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26061. const uv = coord.mul( 2.0 );
  26062. const cx = uv.x.floor();
  26063. const cy = uv.y.floor();
  26064. const result = cx.add( cy ).mod( 2.0 );
  26065. return result.sign();
  26066. } );
  26067. /** @module Shapes **/
  26068. /**
  26069. * Generates a circle based on the uv coordinates.
  26070. *
  26071. * @method
  26072. * @param {Node<vec2>} coord - The uv to generate the circle.
  26073. * @return {Node<float>} The circle shape.
  26074. */
  26075. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26076. const alpha = float( 1 ).toVar();
  26077. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26078. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26079. const dlen = float( len2.fwidth() ).toVar();
  26080. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26081. } else {
  26082. len2.greaterThan( 1.0 ).discard();
  26083. }
  26084. return alpha;
  26085. } );
  26086. // Three.js Transpiler
  26087. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26088. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26089. const f = float( f_immutable ).toVar();
  26090. const t = float( t_immutable ).toVar();
  26091. const b = bool( b_immutable ).toVar();
  26092. return select( b, t, f );
  26093. } ).setLayout( {
  26094. name: 'mx_select',
  26095. type: 'float',
  26096. inputs: [
  26097. { name: 'b', type: 'bool' },
  26098. { name: 't', type: 'float' },
  26099. { name: 'f', type: 'float' }
  26100. ]
  26101. } );
  26102. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26103. const b = bool( b_immutable ).toVar();
  26104. const val = float( val_immutable ).toVar();
  26105. return select( b, val.negate(), val );
  26106. } ).setLayout( {
  26107. name: 'mx_negate_if',
  26108. type: 'float',
  26109. inputs: [
  26110. { name: 'val', type: 'float' },
  26111. { name: 'b', type: 'bool' }
  26112. ]
  26113. } );
  26114. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26115. const x = float( x_immutable ).toVar();
  26116. return int( floor( x ) );
  26117. } ).setLayout( {
  26118. name: 'mx_floor',
  26119. type: 'int',
  26120. inputs: [
  26121. { name: 'x', type: 'float' }
  26122. ]
  26123. } );
  26124. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26125. const x = float( x_immutable ).toVar();
  26126. i.assign( mx_floor( x ) );
  26127. return x.sub( float( i ) );
  26128. } );
  26129. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26130. const t = float( t_immutable ).toVar();
  26131. const s = float( s_immutable ).toVar();
  26132. const v3 = float( v3_immutable ).toVar();
  26133. const v2 = float( v2_immutable ).toVar();
  26134. const v1 = float( v1_immutable ).toVar();
  26135. const v0 = float( v0_immutable ).toVar();
  26136. const s1 = float( sub( 1.0, s ) ).toVar();
  26137. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26138. } ).setLayout( {
  26139. name: 'mx_bilerp_0',
  26140. type: 'float',
  26141. inputs: [
  26142. { name: 'v0', type: 'float' },
  26143. { name: 'v1', type: 'float' },
  26144. { name: 'v2', type: 'float' },
  26145. { name: 'v3', type: 'float' },
  26146. { name: 's', type: 'float' },
  26147. { name: 't', type: 'float' }
  26148. ]
  26149. } );
  26150. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26151. const t = float( t_immutable ).toVar();
  26152. const s = float( s_immutable ).toVar();
  26153. const v3 = vec3( v3_immutable ).toVar();
  26154. const v2 = vec3( v2_immutable ).toVar();
  26155. const v1 = vec3( v1_immutable ).toVar();
  26156. const v0 = vec3( v0_immutable ).toVar();
  26157. const s1 = float( sub( 1.0, s ) ).toVar();
  26158. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26159. } ).setLayout( {
  26160. name: 'mx_bilerp_1',
  26161. type: 'vec3',
  26162. inputs: [
  26163. { name: 'v0', type: 'vec3' },
  26164. { name: 'v1', type: 'vec3' },
  26165. { name: 'v2', type: 'vec3' },
  26166. { name: 'v3', type: 'vec3' },
  26167. { name: 's', type: 'float' },
  26168. { name: 't', type: 'float' }
  26169. ]
  26170. } );
  26171. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26172. 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 ] ) => {
  26173. const r = float( r_immutable ).toVar();
  26174. const t = float( t_immutable ).toVar();
  26175. const s = float( s_immutable ).toVar();
  26176. const v7 = float( v7_immutable ).toVar();
  26177. const v6 = float( v6_immutable ).toVar();
  26178. const v5 = float( v5_immutable ).toVar();
  26179. const v4 = float( v4_immutable ).toVar();
  26180. const v3 = float( v3_immutable ).toVar();
  26181. const v2 = float( v2_immutable ).toVar();
  26182. const v1 = float( v1_immutable ).toVar();
  26183. const v0 = float( v0_immutable ).toVar();
  26184. const s1 = float( sub( 1.0, s ) ).toVar();
  26185. const t1 = float( sub( 1.0, t ) ).toVar();
  26186. const r1 = float( sub( 1.0, r ) ).toVar();
  26187. 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 ) ) ) ) ) );
  26188. } ).setLayout( {
  26189. name: 'mx_trilerp_0',
  26190. type: 'float',
  26191. inputs: [
  26192. { name: 'v0', type: 'float' },
  26193. { name: 'v1', type: 'float' },
  26194. { name: 'v2', type: 'float' },
  26195. { name: 'v3', type: 'float' },
  26196. { name: 'v4', type: 'float' },
  26197. { name: 'v5', type: 'float' },
  26198. { name: 'v6', type: 'float' },
  26199. { name: 'v7', type: 'float' },
  26200. { name: 's', type: 'float' },
  26201. { name: 't', type: 'float' },
  26202. { name: 'r', type: 'float' }
  26203. ]
  26204. } );
  26205. 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 ] ) => {
  26206. const r = float( r_immutable ).toVar();
  26207. const t = float( t_immutable ).toVar();
  26208. const s = float( s_immutable ).toVar();
  26209. const v7 = vec3( v7_immutable ).toVar();
  26210. const v6 = vec3( v6_immutable ).toVar();
  26211. const v5 = vec3( v5_immutable ).toVar();
  26212. const v4 = vec3( v4_immutable ).toVar();
  26213. const v3 = vec3( v3_immutable ).toVar();
  26214. const v2 = vec3( v2_immutable ).toVar();
  26215. const v1 = vec3( v1_immutable ).toVar();
  26216. const v0 = vec3( v0_immutable ).toVar();
  26217. const s1 = float( sub( 1.0, s ) ).toVar();
  26218. const t1 = float( sub( 1.0, t ) ).toVar();
  26219. const r1 = float( sub( 1.0, r ) ).toVar();
  26220. 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 ) ) ) ) ) );
  26221. } ).setLayout( {
  26222. name: 'mx_trilerp_1',
  26223. type: 'vec3',
  26224. inputs: [
  26225. { name: 'v0', type: 'vec3' },
  26226. { name: 'v1', type: 'vec3' },
  26227. { name: 'v2', type: 'vec3' },
  26228. { name: 'v3', type: 'vec3' },
  26229. { name: 'v4', type: 'vec3' },
  26230. { name: 'v5', type: 'vec3' },
  26231. { name: 'v6', type: 'vec3' },
  26232. { name: 'v7', type: 'vec3' },
  26233. { name: 's', type: 'float' },
  26234. { name: 't', type: 'float' },
  26235. { name: 'r', type: 'float' }
  26236. ]
  26237. } );
  26238. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26239. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26240. const y = float( y_immutable ).toVar();
  26241. const x = float( x_immutable ).toVar();
  26242. const hash = uint( hash_immutable ).toVar();
  26243. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26244. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26245. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26246. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26247. } ).setLayout( {
  26248. name: 'mx_gradient_float_0',
  26249. type: 'float',
  26250. inputs: [
  26251. { name: 'hash', type: 'uint' },
  26252. { name: 'x', type: 'float' },
  26253. { name: 'y', type: 'float' }
  26254. ]
  26255. } );
  26256. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26257. const z = float( z_immutable ).toVar();
  26258. const y = float( y_immutable ).toVar();
  26259. const x = float( x_immutable ).toVar();
  26260. const hash = uint( hash_immutable ).toVar();
  26261. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26262. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26263. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26264. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26265. } ).setLayout( {
  26266. name: 'mx_gradient_float_1',
  26267. type: 'float',
  26268. inputs: [
  26269. { name: 'hash', type: 'uint' },
  26270. { name: 'x', type: 'float' },
  26271. { name: 'y', type: 'float' },
  26272. { name: 'z', type: 'float' }
  26273. ]
  26274. } );
  26275. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26276. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26277. const y = float( y_immutable ).toVar();
  26278. const x = float( x_immutable ).toVar();
  26279. const hash = uvec3( hash_immutable ).toVar();
  26280. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26281. } ).setLayout( {
  26282. name: 'mx_gradient_vec3_0',
  26283. type: 'vec3',
  26284. inputs: [
  26285. { name: 'hash', type: 'uvec3' },
  26286. { name: 'x', type: 'float' },
  26287. { name: 'y', type: 'float' }
  26288. ]
  26289. } );
  26290. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26291. const z = float( z_immutable ).toVar();
  26292. const y = float( y_immutable ).toVar();
  26293. const x = float( x_immutable ).toVar();
  26294. const hash = uvec3( hash_immutable ).toVar();
  26295. 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 ) );
  26296. } ).setLayout( {
  26297. name: 'mx_gradient_vec3_1',
  26298. type: 'vec3',
  26299. inputs: [
  26300. { name: 'hash', type: 'uvec3' },
  26301. { name: 'x', type: 'float' },
  26302. { name: 'y', type: 'float' },
  26303. { name: 'z', type: 'float' }
  26304. ]
  26305. } );
  26306. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26307. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26308. const v = float( v_immutable ).toVar();
  26309. return mul( 0.6616, v );
  26310. } ).setLayout( {
  26311. name: 'mx_gradient_scale2d_0',
  26312. type: 'float',
  26313. inputs: [
  26314. { name: 'v', type: 'float' }
  26315. ]
  26316. } );
  26317. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26318. const v = float( v_immutable ).toVar();
  26319. return mul( 0.9820, v );
  26320. } ).setLayout( {
  26321. name: 'mx_gradient_scale3d_0',
  26322. type: 'float',
  26323. inputs: [
  26324. { name: 'v', type: 'float' }
  26325. ]
  26326. } );
  26327. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26328. const v = vec3( v_immutable ).toVar();
  26329. return mul( 0.6616, v );
  26330. } ).setLayout( {
  26331. name: 'mx_gradient_scale2d_1',
  26332. type: 'vec3',
  26333. inputs: [
  26334. { name: 'v', type: 'vec3' }
  26335. ]
  26336. } );
  26337. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26338. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26339. const v = vec3( v_immutable ).toVar();
  26340. return mul( 0.9820, v );
  26341. } ).setLayout( {
  26342. name: 'mx_gradient_scale3d_1',
  26343. type: 'vec3',
  26344. inputs: [
  26345. { name: 'v', type: 'vec3' }
  26346. ]
  26347. } );
  26348. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26349. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26350. const k = int( k_immutable ).toVar();
  26351. const x = uint( x_immutable ).toVar();
  26352. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26353. } ).setLayout( {
  26354. name: 'mx_rotl32',
  26355. type: 'uint',
  26356. inputs: [
  26357. { name: 'x', type: 'uint' },
  26358. { name: 'k', type: 'int' }
  26359. ]
  26360. } );
  26361. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26362. a.subAssign( c );
  26363. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26364. c.addAssign( b );
  26365. b.subAssign( a );
  26366. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26367. a.addAssign( c );
  26368. c.subAssign( b );
  26369. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26370. b.addAssign( a );
  26371. a.subAssign( c );
  26372. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26373. c.addAssign( b );
  26374. b.subAssign( a );
  26375. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26376. a.addAssign( c );
  26377. c.subAssign( b );
  26378. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26379. b.addAssign( a );
  26380. } );
  26381. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26382. const c = uint( c_immutable ).toVar();
  26383. const b = uint( b_immutable ).toVar();
  26384. const a = uint( a_immutable ).toVar();
  26385. c.bitXorAssign( b );
  26386. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26387. a.bitXorAssign( c );
  26388. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26389. b.bitXorAssign( a );
  26390. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26391. c.bitXorAssign( b );
  26392. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26393. a.bitXorAssign( c );
  26394. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26395. b.bitXorAssign( a );
  26396. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26397. c.bitXorAssign( b );
  26398. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26399. return c;
  26400. } ).setLayout( {
  26401. name: 'mx_bjfinal',
  26402. type: 'uint',
  26403. inputs: [
  26404. { name: 'a', type: 'uint' },
  26405. { name: 'b', type: 'uint' },
  26406. { name: 'c', type: 'uint' }
  26407. ]
  26408. } );
  26409. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26410. const bits = uint( bits_immutable ).toVar();
  26411. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26412. } ).setLayout( {
  26413. name: 'mx_bits_to_01',
  26414. type: 'float',
  26415. inputs: [
  26416. { name: 'bits', type: 'uint' }
  26417. ]
  26418. } );
  26419. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26420. const t = float( t_immutable ).toVar();
  26421. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26422. } ).setLayout( {
  26423. name: 'mx_fade',
  26424. type: 'float',
  26425. inputs: [
  26426. { name: 't', type: 'float' }
  26427. ]
  26428. } );
  26429. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26430. const x = int( x_immutable ).toVar();
  26431. const len = uint( uint( 1 ) ).toVar();
  26432. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26433. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26434. } ).setLayout( {
  26435. name: 'mx_hash_int_0',
  26436. type: 'uint',
  26437. inputs: [
  26438. { name: 'x', type: 'int' }
  26439. ]
  26440. } );
  26441. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26442. const y = int( y_immutable ).toVar();
  26443. const x = int( x_immutable ).toVar();
  26444. const len = uint( uint( 2 ) ).toVar();
  26445. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26446. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26447. a.addAssign( uint( x ) );
  26448. b.addAssign( uint( y ) );
  26449. return mx_bjfinal( a, b, c );
  26450. } ).setLayout( {
  26451. name: 'mx_hash_int_1',
  26452. type: 'uint',
  26453. inputs: [
  26454. { name: 'x', type: 'int' },
  26455. { name: 'y', type: 'int' }
  26456. ]
  26457. } );
  26458. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26459. const z = int( z_immutable ).toVar();
  26460. const y = int( y_immutable ).toVar();
  26461. const x = int( x_immutable ).toVar();
  26462. const len = uint( uint( 3 ) ).toVar();
  26463. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26464. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26465. a.addAssign( uint( x ) );
  26466. b.addAssign( uint( y ) );
  26467. c.addAssign( uint( z ) );
  26468. return mx_bjfinal( a, b, c );
  26469. } ).setLayout( {
  26470. name: 'mx_hash_int_2',
  26471. type: 'uint',
  26472. inputs: [
  26473. { name: 'x', type: 'int' },
  26474. { name: 'y', type: 'int' },
  26475. { name: 'z', type: 'int' }
  26476. ]
  26477. } );
  26478. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26479. const xx = int( xx_immutable ).toVar();
  26480. const z = int( z_immutable ).toVar();
  26481. const y = int( y_immutable ).toVar();
  26482. const x = int( x_immutable ).toVar();
  26483. const len = uint( uint( 4 ) ).toVar();
  26484. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26485. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26486. a.addAssign( uint( x ) );
  26487. b.addAssign( uint( y ) );
  26488. c.addAssign( uint( z ) );
  26489. mx_bjmix( a, b, c );
  26490. a.addAssign( uint( xx ) );
  26491. return mx_bjfinal( a, b, c );
  26492. } ).setLayout( {
  26493. name: 'mx_hash_int_3',
  26494. type: 'uint',
  26495. inputs: [
  26496. { name: 'x', type: 'int' },
  26497. { name: 'y', type: 'int' },
  26498. { name: 'z', type: 'int' },
  26499. { name: 'xx', type: 'int' }
  26500. ]
  26501. } );
  26502. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26503. const yy = int( yy_immutable ).toVar();
  26504. const xx = int( xx_immutable ).toVar();
  26505. const z = int( z_immutable ).toVar();
  26506. const y = int( y_immutable ).toVar();
  26507. const x = int( x_immutable ).toVar();
  26508. const len = uint( uint( 5 ) ).toVar();
  26509. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26510. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26511. a.addAssign( uint( x ) );
  26512. b.addAssign( uint( y ) );
  26513. c.addAssign( uint( z ) );
  26514. mx_bjmix( a, b, c );
  26515. a.addAssign( uint( xx ) );
  26516. b.addAssign( uint( yy ) );
  26517. return mx_bjfinal( a, b, c );
  26518. } ).setLayout( {
  26519. name: 'mx_hash_int_4',
  26520. type: 'uint',
  26521. inputs: [
  26522. { name: 'x', type: 'int' },
  26523. { name: 'y', type: 'int' },
  26524. { name: 'z', type: 'int' },
  26525. { name: 'xx', type: 'int' },
  26526. { name: 'yy', type: 'int' }
  26527. ]
  26528. } );
  26529. 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 ] );
  26530. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26531. const y = int( y_immutable ).toVar();
  26532. const x = int( x_immutable ).toVar();
  26533. const h = uint( mx_hash_int( x, y ) ).toVar();
  26534. const result = uvec3().toVar();
  26535. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26536. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26537. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26538. return result;
  26539. } ).setLayout( {
  26540. name: 'mx_hash_vec3_0',
  26541. type: 'uvec3',
  26542. inputs: [
  26543. { name: 'x', type: 'int' },
  26544. { name: 'y', type: 'int' }
  26545. ]
  26546. } );
  26547. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26548. const z = int( z_immutable ).toVar();
  26549. const y = int( y_immutable ).toVar();
  26550. const x = int( x_immutable ).toVar();
  26551. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26552. const result = uvec3().toVar();
  26553. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26554. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26555. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26556. return result;
  26557. } ).setLayout( {
  26558. name: 'mx_hash_vec3_1',
  26559. type: 'uvec3',
  26560. inputs: [
  26561. { name: 'x', type: 'int' },
  26562. { name: 'y', type: 'int' },
  26563. { name: 'z', type: 'int' }
  26564. ]
  26565. } );
  26566. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26567. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26568. const p = vec2( p_immutable ).toVar();
  26569. const X = int().toVar(), Y = int().toVar();
  26570. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26571. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26572. const u = float( mx_fade( fx ) ).toVar();
  26573. const v = float( mx_fade( fy ) ).toVar();
  26574. 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();
  26575. return mx_gradient_scale2d( result );
  26576. } ).setLayout( {
  26577. name: 'mx_perlin_noise_float_0',
  26578. type: 'float',
  26579. inputs: [
  26580. { name: 'p', type: 'vec2' }
  26581. ]
  26582. } );
  26583. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26584. const p = vec3( p_immutable ).toVar();
  26585. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26586. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26587. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26588. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26589. const u = float( mx_fade( fx ) ).toVar();
  26590. const v = float( mx_fade( fy ) ).toVar();
  26591. const w = float( mx_fade( fz ) ).toVar();
  26592. 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();
  26593. return mx_gradient_scale3d( result );
  26594. } ).setLayout( {
  26595. name: 'mx_perlin_noise_float_1',
  26596. type: 'float',
  26597. inputs: [
  26598. { name: 'p', type: 'vec3' }
  26599. ]
  26600. } );
  26601. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26602. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26603. const p = vec2( p_immutable ).toVar();
  26604. const X = int().toVar(), Y = int().toVar();
  26605. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26606. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26607. const u = float( mx_fade( fx ) ).toVar();
  26608. const v = float( mx_fade( fy ) ).toVar();
  26609. 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();
  26610. return mx_gradient_scale2d( result );
  26611. } ).setLayout( {
  26612. name: 'mx_perlin_noise_vec3_0',
  26613. type: 'vec3',
  26614. inputs: [
  26615. { name: 'p', type: 'vec2' }
  26616. ]
  26617. } );
  26618. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26619. const p = vec3( p_immutable ).toVar();
  26620. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26621. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26622. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26623. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26624. const u = float( mx_fade( fx ) ).toVar();
  26625. const v = float( mx_fade( fy ) ).toVar();
  26626. const w = float( mx_fade( fz ) ).toVar();
  26627. 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();
  26628. return mx_gradient_scale3d( result );
  26629. } ).setLayout( {
  26630. name: 'mx_perlin_noise_vec3_1',
  26631. type: 'vec3',
  26632. inputs: [
  26633. { name: 'p', type: 'vec3' }
  26634. ]
  26635. } );
  26636. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26637. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26638. const p = float( p_immutable ).toVar();
  26639. const ix = int( mx_floor( p ) ).toVar();
  26640. return mx_bits_to_01( mx_hash_int( ix ) );
  26641. } ).setLayout( {
  26642. name: 'mx_cell_noise_float_0',
  26643. type: 'float',
  26644. inputs: [
  26645. { name: 'p', type: 'float' }
  26646. ]
  26647. } );
  26648. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26649. const p = vec2( p_immutable ).toVar();
  26650. const ix = int( mx_floor( p.x ) ).toVar();
  26651. const iy = int( mx_floor( p.y ) ).toVar();
  26652. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26653. } ).setLayout( {
  26654. name: 'mx_cell_noise_float_1',
  26655. type: 'float',
  26656. inputs: [
  26657. { name: 'p', type: 'vec2' }
  26658. ]
  26659. } );
  26660. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26661. const p = vec3( p_immutable ).toVar();
  26662. const ix = int( mx_floor( p.x ) ).toVar();
  26663. const iy = int( mx_floor( p.y ) ).toVar();
  26664. const iz = int( mx_floor( p.z ) ).toVar();
  26665. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26666. } ).setLayout( {
  26667. name: 'mx_cell_noise_float_2',
  26668. type: 'float',
  26669. inputs: [
  26670. { name: 'p', type: 'vec3' }
  26671. ]
  26672. } );
  26673. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26674. const p = vec4( p_immutable ).toVar();
  26675. const ix = int( mx_floor( p.x ) ).toVar();
  26676. const iy = int( mx_floor( p.y ) ).toVar();
  26677. const iz = int( mx_floor( p.z ) ).toVar();
  26678. const iw = int( mx_floor( p.w ) ).toVar();
  26679. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26680. } ).setLayout( {
  26681. name: 'mx_cell_noise_float_3',
  26682. type: 'float',
  26683. inputs: [
  26684. { name: 'p', type: 'vec4' }
  26685. ]
  26686. } );
  26687. 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 ] );
  26688. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26689. const p = float( p_immutable ).toVar();
  26690. const ix = int( mx_floor( p ) ).toVar();
  26691. 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 ) ) ) );
  26692. } ).setLayout( {
  26693. name: 'mx_cell_noise_vec3_0',
  26694. type: 'vec3',
  26695. inputs: [
  26696. { name: 'p', type: 'float' }
  26697. ]
  26698. } );
  26699. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26700. const p = vec2( p_immutable ).toVar();
  26701. const ix = int( mx_floor( p.x ) ).toVar();
  26702. const iy = int( mx_floor( p.y ) ).toVar();
  26703. 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 ) ) ) );
  26704. } ).setLayout( {
  26705. name: 'mx_cell_noise_vec3_1',
  26706. type: 'vec3',
  26707. inputs: [
  26708. { name: 'p', type: 'vec2' }
  26709. ]
  26710. } );
  26711. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26712. const p = vec3( p_immutable ).toVar();
  26713. const ix = int( mx_floor( p.x ) ).toVar();
  26714. const iy = int( mx_floor( p.y ) ).toVar();
  26715. const iz = int( mx_floor( p.z ) ).toVar();
  26716. 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 ) ) ) );
  26717. } ).setLayout( {
  26718. name: 'mx_cell_noise_vec3_2',
  26719. type: 'vec3',
  26720. inputs: [
  26721. { name: 'p', type: 'vec3' }
  26722. ]
  26723. } );
  26724. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26725. const p = vec4( p_immutable ).toVar();
  26726. const ix = int( mx_floor( p.x ) ).toVar();
  26727. const iy = int( mx_floor( p.y ) ).toVar();
  26728. const iz = int( mx_floor( p.z ) ).toVar();
  26729. const iw = int( mx_floor( p.w ) ).toVar();
  26730. 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 ) ) ) );
  26731. } ).setLayout( {
  26732. name: 'mx_cell_noise_vec3_3',
  26733. type: 'vec3',
  26734. inputs: [
  26735. { name: 'p', type: 'vec4' }
  26736. ]
  26737. } );
  26738. 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 ] );
  26739. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26740. const diminish = float( diminish_immutable ).toVar();
  26741. const lacunarity = float( lacunarity_immutable ).toVar();
  26742. const octaves = int( octaves_immutable ).toVar();
  26743. const p = vec3( p_immutable ).toVar();
  26744. const result = float( 0.0 ).toVar();
  26745. const amplitude = float( 1.0 ).toVar();
  26746. Loop( octaves, () => {
  26747. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26748. amplitude.mulAssign( diminish );
  26749. p.mulAssign( lacunarity );
  26750. } );
  26751. return result;
  26752. } ).setLayout( {
  26753. name: 'mx_fractal_noise_float',
  26754. type: 'float',
  26755. inputs: [
  26756. { name: 'p', type: 'vec3' },
  26757. { name: 'octaves', type: 'int' },
  26758. { name: 'lacunarity', type: 'float' },
  26759. { name: 'diminish', type: 'float' }
  26760. ]
  26761. } );
  26762. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26763. const diminish = float( diminish_immutable ).toVar();
  26764. const lacunarity = float( lacunarity_immutable ).toVar();
  26765. const octaves = int( octaves_immutable ).toVar();
  26766. const p = vec3( p_immutable ).toVar();
  26767. const result = vec3( 0.0 ).toVar();
  26768. const amplitude = float( 1.0 ).toVar();
  26769. Loop( octaves, () => {
  26770. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26771. amplitude.mulAssign( diminish );
  26772. p.mulAssign( lacunarity );
  26773. } );
  26774. return result;
  26775. } ).setLayout( {
  26776. name: 'mx_fractal_noise_vec3',
  26777. type: 'vec3',
  26778. inputs: [
  26779. { name: 'p', type: 'vec3' },
  26780. { name: 'octaves', type: 'int' },
  26781. { name: 'lacunarity', type: 'float' },
  26782. { name: 'diminish', type: 'float' }
  26783. ]
  26784. } );
  26785. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26786. const diminish = float( diminish_immutable ).toVar();
  26787. const lacunarity = float( lacunarity_immutable ).toVar();
  26788. const octaves = int( octaves_immutable ).toVar();
  26789. const p = vec3( p_immutable ).toVar();
  26790. 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 ) );
  26791. } ).setLayout( {
  26792. name: 'mx_fractal_noise_vec2',
  26793. type: 'vec2',
  26794. inputs: [
  26795. { name: 'p', type: 'vec3' },
  26796. { name: 'octaves', type: 'int' },
  26797. { name: 'lacunarity', type: 'float' },
  26798. { name: 'diminish', type: 'float' }
  26799. ]
  26800. } );
  26801. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26802. const diminish = float( diminish_immutable ).toVar();
  26803. const lacunarity = float( lacunarity_immutable ).toVar();
  26804. const octaves = int( octaves_immutable ).toVar();
  26805. const p = vec3( p_immutable ).toVar();
  26806. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26807. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26808. return vec4( c, f );
  26809. } ).setLayout( {
  26810. name: 'mx_fractal_noise_vec4',
  26811. type: 'vec4',
  26812. inputs: [
  26813. { name: 'p', type: 'vec3' },
  26814. { name: 'octaves', type: 'int' },
  26815. { name: 'lacunarity', type: 'float' },
  26816. { name: 'diminish', type: 'float' }
  26817. ]
  26818. } );
  26819. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26820. const metric = int( metric_immutable ).toVar();
  26821. const jitter = float( jitter_immutable ).toVar();
  26822. const yoff = int( yoff_immutable ).toVar();
  26823. const xoff = int( xoff_immutable ).toVar();
  26824. const y = int( y_immutable ).toVar();
  26825. const x = int( x_immutable ).toVar();
  26826. const p = vec2( p_immutable ).toVar();
  26827. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26828. const off = vec2( tmp.x, tmp.y ).toVar();
  26829. off.subAssign( 0.5 );
  26830. off.mulAssign( jitter );
  26831. off.addAssign( 0.5 );
  26832. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26833. const diff = vec2( cellpos.sub( p ) ).toVar();
  26834. If( metric.equal( int( 2 ) ), () => {
  26835. return abs( diff.x ).add( abs( diff.y ) );
  26836. } );
  26837. If( metric.equal( int( 3 ) ), () => {
  26838. return max$1( abs( diff.x ), abs( diff.y ) );
  26839. } );
  26840. return dot( diff, diff );
  26841. } ).setLayout( {
  26842. name: 'mx_worley_distance_0',
  26843. type: 'float',
  26844. inputs: [
  26845. { name: 'p', type: 'vec2' },
  26846. { name: 'x', type: 'int' },
  26847. { name: 'y', type: 'int' },
  26848. { name: 'xoff', type: 'int' },
  26849. { name: 'yoff', type: 'int' },
  26850. { name: 'jitter', type: 'float' },
  26851. { name: 'metric', type: 'int' }
  26852. ]
  26853. } );
  26854. 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 ] ) => {
  26855. const metric = int( metric_immutable ).toVar();
  26856. const jitter = float( jitter_immutable ).toVar();
  26857. const zoff = int( zoff_immutable ).toVar();
  26858. const yoff = int( yoff_immutable ).toVar();
  26859. const xoff = int( xoff_immutable ).toVar();
  26860. const z = int( z_immutable ).toVar();
  26861. const y = int( y_immutable ).toVar();
  26862. const x = int( x_immutable ).toVar();
  26863. const p = vec3( p_immutable ).toVar();
  26864. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26865. off.subAssign( 0.5 );
  26866. off.mulAssign( jitter );
  26867. off.addAssign( 0.5 );
  26868. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26869. const diff = vec3( cellpos.sub( p ) ).toVar();
  26870. If( metric.equal( int( 2 ) ), () => {
  26871. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26872. } );
  26873. If( metric.equal( int( 3 ) ), () => {
  26874. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26875. } );
  26876. return dot( diff, diff );
  26877. } ).setLayout( {
  26878. name: 'mx_worley_distance_1',
  26879. type: 'float',
  26880. inputs: [
  26881. { name: 'p', type: 'vec3' },
  26882. { name: 'x', type: 'int' },
  26883. { name: 'y', type: 'int' },
  26884. { name: 'z', type: 'int' },
  26885. { name: 'xoff', type: 'int' },
  26886. { name: 'yoff', type: 'int' },
  26887. { name: 'zoff', type: 'int' },
  26888. { name: 'jitter', type: 'float' },
  26889. { name: 'metric', type: 'int' }
  26890. ]
  26891. } );
  26892. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26893. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26894. const metric = int( metric_immutable ).toVar();
  26895. const jitter = float( jitter_immutable ).toVar();
  26896. const p = vec2( p_immutable ).toVar();
  26897. const X = int().toVar(), Y = int().toVar();
  26898. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26899. const sqdist = float( 1e6 ).toVar();
  26900. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26901. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26902. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26903. sqdist.assign( min$1( sqdist, dist ) );
  26904. } );
  26905. } );
  26906. If( metric.equal( int( 0 ) ), () => {
  26907. sqdist.assign( sqrt( sqdist ) );
  26908. } );
  26909. return sqdist;
  26910. } ).setLayout( {
  26911. name: 'mx_worley_noise_float_0',
  26912. type: 'float',
  26913. inputs: [
  26914. { name: 'p', type: 'vec2' },
  26915. { name: 'jitter', type: 'float' },
  26916. { name: 'metric', type: 'int' }
  26917. ]
  26918. } );
  26919. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26920. const metric = int( metric_immutable ).toVar();
  26921. const jitter = float( jitter_immutable ).toVar();
  26922. const p = vec2( p_immutable ).toVar();
  26923. const X = int().toVar(), Y = int().toVar();
  26924. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26925. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26926. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26927. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26928. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26929. If( dist.lessThan( sqdist.x ), () => {
  26930. sqdist.y.assign( sqdist.x );
  26931. sqdist.x.assign( dist );
  26932. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26933. sqdist.y.assign( dist );
  26934. } );
  26935. } );
  26936. } );
  26937. If( metric.equal( int( 0 ) ), () => {
  26938. sqdist.assign( sqrt( sqdist ) );
  26939. } );
  26940. return sqdist;
  26941. } ).setLayout( {
  26942. name: 'mx_worley_noise_vec2_0',
  26943. type: 'vec2',
  26944. inputs: [
  26945. { name: 'p', type: 'vec2' },
  26946. { name: 'jitter', type: 'float' },
  26947. { name: 'metric', type: 'int' }
  26948. ]
  26949. } );
  26950. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26951. const metric = int( metric_immutable ).toVar();
  26952. const jitter = float( jitter_immutable ).toVar();
  26953. const p = vec2( p_immutable ).toVar();
  26954. const X = int().toVar(), Y = int().toVar();
  26955. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26956. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26957. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26958. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26959. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26960. If( dist.lessThan( sqdist.x ), () => {
  26961. sqdist.z.assign( sqdist.y );
  26962. sqdist.y.assign( sqdist.x );
  26963. sqdist.x.assign( dist );
  26964. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26965. sqdist.z.assign( sqdist.y );
  26966. sqdist.y.assign( dist );
  26967. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26968. sqdist.z.assign( dist );
  26969. } );
  26970. } );
  26971. } );
  26972. If( metric.equal( int( 0 ) ), () => {
  26973. sqdist.assign( sqrt( sqdist ) );
  26974. } );
  26975. return sqdist;
  26976. } ).setLayout( {
  26977. name: 'mx_worley_noise_vec3_0',
  26978. type: 'vec3',
  26979. inputs: [
  26980. { name: 'p', type: 'vec2' },
  26981. { name: 'jitter', type: 'float' },
  26982. { name: 'metric', type: 'int' }
  26983. ]
  26984. } );
  26985. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26986. const metric = int( metric_immutable ).toVar();
  26987. const jitter = float( jitter_immutable ).toVar();
  26988. const p = vec3( p_immutable ).toVar();
  26989. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26990. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26991. const sqdist = float( 1e6 ).toVar();
  26992. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26993. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26994. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26995. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26996. sqdist.assign( min$1( sqdist, dist ) );
  26997. } );
  26998. } );
  26999. } );
  27000. If( metric.equal( int( 0 ) ), () => {
  27001. sqdist.assign( sqrt( sqdist ) );
  27002. } );
  27003. return sqdist;
  27004. } ).setLayout( {
  27005. name: 'mx_worley_noise_float_1',
  27006. type: 'float',
  27007. inputs: [
  27008. { name: 'p', type: 'vec3' },
  27009. { name: 'jitter', type: 'float' },
  27010. { name: 'metric', type: 'int' }
  27011. ]
  27012. } );
  27013. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27014. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27015. const metric = int( metric_immutable ).toVar();
  27016. const jitter = float( jitter_immutable ).toVar();
  27017. const p = vec3( p_immutable ).toVar();
  27018. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27019. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27020. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27021. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27022. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27023. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27024. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27025. If( dist.lessThan( sqdist.x ), () => {
  27026. sqdist.y.assign( sqdist.x );
  27027. sqdist.x.assign( dist );
  27028. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27029. sqdist.y.assign( dist );
  27030. } );
  27031. } );
  27032. } );
  27033. } );
  27034. If( metric.equal( int( 0 ) ), () => {
  27035. sqdist.assign( sqrt( sqdist ) );
  27036. } );
  27037. return sqdist;
  27038. } ).setLayout( {
  27039. name: 'mx_worley_noise_vec2_1',
  27040. type: 'vec2',
  27041. inputs: [
  27042. { name: 'p', type: 'vec3' },
  27043. { name: 'jitter', type: 'float' },
  27044. { name: 'metric', type: 'int' }
  27045. ]
  27046. } );
  27047. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27048. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27049. const metric = int( metric_immutable ).toVar();
  27050. const jitter = float( jitter_immutable ).toVar();
  27051. const p = vec3( p_immutable ).toVar();
  27052. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27053. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27054. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27055. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27056. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27057. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27058. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27059. If( dist.lessThan( sqdist.x ), () => {
  27060. sqdist.z.assign( sqdist.y );
  27061. sqdist.y.assign( sqdist.x );
  27062. sqdist.x.assign( dist );
  27063. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27064. sqdist.z.assign( sqdist.y );
  27065. sqdist.y.assign( dist );
  27066. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27067. sqdist.z.assign( dist );
  27068. } );
  27069. } );
  27070. } );
  27071. } );
  27072. If( metric.equal( int( 0 ) ), () => {
  27073. sqdist.assign( sqrt( sqdist ) );
  27074. } );
  27075. return sqdist;
  27076. } ).setLayout( {
  27077. name: 'mx_worley_noise_vec3_1',
  27078. type: 'vec3',
  27079. inputs: [
  27080. { name: 'p', type: 'vec3' },
  27081. { name: 'jitter', type: 'float' },
  27082. { name: 'metric', type: 'int' }
  27083. ]
  27084. } );
  27085. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27086. // Three.js Transpiler
  27087. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27088. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27089. const s = hsv.y;
  27090. const v = hsv.z;
  27091. const result = vec3().toVar();
  27092. If( s.lessThan( 0.0001 ), () => {
  27093. result.assign( vec3( v, v, v ) );
  27094. } ).Else( () => {
  27095. let h = hsv.x;
  27096. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27097. const hi = int( trunc( h ) );
  27098. const f = h.sub( float( hi ) );
  27099. const p = v.mul( s.oneMinus() );
  27100. const q = v.mul( s.mul( f ).oneMinus() );
  27101. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27102. If( hi.equal( int( 0 ) ), () => {
  27103. result.assign( vec3( v, t, p ) );
  27104. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27105. result.assign( vec3( q, v, p ) );
  27106. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27107. result.assign( vec3( p, v, t ) );
  27108. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27109. result.assign( vec3( p, q, v ) );
  27110. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27111. result.assign( vec3( t, p, v ) );
  27112. } ).Else( () => {
  27113. result.assign( vec3( v, p, q ) );
  27114. } );
  27115. } );
  27116. return result;
  27117. } ).setLayout( {
  27118. name: 'mx_hsvtorgb',
  27119. type: 'vec3',
  27120. inputs: [
  27121. { name: 'hsv', type: 'vec3' }
  27122. ]
  27123. } );
  27124. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27125. const c = vec3( c_immutable ).toVar();
  27126. const r = float( c.x ).toVar();
  27127. const g = float( c.y ).toVar();
  27128. const b = float( c.z ).toVar();
  27129. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27130. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27131. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27132. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27133. v.assign( maxcomp );
  27134. If( maxcomp.greaterThan( 0.0 ), () => {
  27135. s.assign( delta.div( maxcomp ) );
  27136. } ).Else( () => {
  27137. s.assign( 0.0 );
  27138. } );
  27139. If( s.lessThanEqual( 0.0 ), () => {
  27140. h.assign( 0.0 );
  27141. } ).Else( () => {
  27142. If( r.greaterThanEqual( maxcomp ), () => {
  27143. h.assign( g.sub( b ).div( delta ) );
  27144. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27145. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27146. } ).Else( () => {
  27147. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27148. } );
  27149. h.mulAssign( 1.0 / 6.0 );
  27150. If( h.lessThan( 0.0 ), () => {
  27151. h.addAssign( 1.0 );
  27152. } );
  27153. } );
  27154. return vec3( h, s, v );
  27155. } ).setLayout( {
  27156. name: 'mx_rgbtohsv',
  27157. type: 'vec3',
  27158. inputs: [
  27159. { name: 'c', type: 'vec3' }
  27160. ]
  27161. } );
  27162. // Three.js Transpiler
  27163. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27164. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27165. const color = vec3( color_immutable ).toVar();
  27166. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27167. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27168. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27169. return mix( linSeg, powSeg, isAbove );
  27170. } ).setLayout( {
  27171. name: 'mx_srgb_texture_to_lin_rec709',
  27172. type: 'vec3',
  27173. inputs: [
  27174. { name: 'color', type: 'vec3' }
  27175. ]
  27176. } );
  27177. const mx_aastep = ( threshold, value ) => {
  27178. threshold = float( threshold );
  27179. value = float( value );
  27180. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27181. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27182. };
  27183. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27184. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27185. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27186. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27187. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27188. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27189. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27190. const mx_safepower = ( in1, in2 = 1 ) => {
  27191. in1 = float( in1 );
  27192. return in1.abs().pow( in2 ).mul( in1.sign() );
  27193. };
  27194. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27195. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27196. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27197. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27198. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27199. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27200. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27201. return noise_vec4.mul( amplitude ).add( pivot );
  27202. };
  27203. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27204. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27205. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27206. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27207. 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 );
  27208. 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 );
  27209. 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 );
  27210. 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 );
  27211. /** @module getParallaxCorrectNormal **/
  27212. /**
  27213. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27214. *
  27215. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27216. *
  27217. * ```js
  27218. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27219. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27220. * ```
  27221. * @function
  27222. * @param {Node<vec3>} normal - The normal to correct.
  27223. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27224. * @param {Node<vec3>} cubePos - The cube position.
  27225. * @return {Node<vec3>} The parallax corrected normal.
  27226. */
  27227. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27228. const nDir = normalize( normal ).toVar( 'nDir' );
  27229. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27230. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27231. const rbminmax = vec3().toVar( 'rbminmax' );
  27232. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27233. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27234. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27235. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27236. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27237. return boxIntersection.sub( cubePos );
  27238. } );
  27239. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27240. // normal is assumed to have unit length
  27241. const x = normal.x, y = normal.y, z = normal.z;
  27242. // band 0
  27243. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27244. // band 1
  27245. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27246. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27247. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27248. // band 2
  27249. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27250. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27251. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27252. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27253. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27254. return result;
  27255. } );
  27256. // constants
  27257. var TSL = /*#__PURE__*/Object.freeze({
  27258. __proto__: null,
  27259. BRDF_GGX: BRDF_GGX,
  27260. BRDF_Lambert: BRDF_Lambert,
  27261. BasicShadowFilter: BasicShadowFilter,
  27262. Break: Break,
  27263. Const: Const,
  27264. Continue: Continue,
  27265. DFGApprox: DFGApprox,
  27266. D_GGX: D_GGX,
  27267. Discard: Discard,
  27268. EPSILON: EPSILON,
  27269. F_Schlick: F_Schlick,
  27270. Fn: Fn,
  27271. INFINITY: INFINITY,
  27272. If: If,
  27273. Loop: Loop,
  27274. NodeAccess: NodeAccess,
  27275. NodeShaderStage: NodeShaderStage,
  27276. NodeType: NodeType,
  27277. NodeUpdateType: NodeUpdateType,
  27278. PCFShadowFilter: PCFShadowFilter,
  27279. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27280. PI: PI,
  27281. PI2: PI2,
  27282. Return: Return,
  27283. Schlick_to_F0: Schlick_to_F0,
  27284. ScriptableNodeResources: ScriptableNodeResources,
  27285. ShaderNode: ShaderNode,
  27286. TBNViewMatrix: TBNViewMatrix,
  27287. VSMShadowFilter: VSMShadowFilter,
  27288. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27289. Var: Var,
  27290. abs: abs,
  27291. acesFilmicToneMapping: acesFilmicToneMapping,
  27292. acos: acos,
  27293. add: add,
  27294. addMethodChaining: addMethodChaining,
  27295. addNodeElement: addNodeElement,
  27296. agxToneMapping: agxToneMapping,
  27297. all: all,
  27298. alphaT: alphaT,
  27299. and: and,
  27300. anisotropy: anisotropy,
  27301. anisotropyB: anisotropyB,
  27302. anisotropyT: anisotropyT,
  27303. any: any,
  27304. append: append,
  27305. arrayBuffer: arrayBuffer,
  27306. asin: asin,
  27307. assign: assign,
  27308. atan: atan,
  27309. atan2: atan2,
  27310. atomicAdd: atomicAdd,
  27311. atomicAnd: atomicAnd,
  27312. atomicFunc: atomicFunc,
  27313. atomicMax: atomicMax,
  27314. atomicMin: atomicMin,
  27315. atomicOr: atomicOr,
  27316. atomicStore: atomicStore,
  27317. atomicSub: atomicSub,
  27318. atomicXor: atomicXor,
  27319. attenuationColor: attenuationColor,
  27320. attenuationDistance: attenuationDistance,
  27321. attribute: attribute,
  27322. attributeArray: attributeArray,
  27323. backgroundBlurriness: backgroundBlurriness,
  27324. backgroundIntensity: backgroundIntensity,
  27325. backgroundRotation: backgroundRotation,
  27326. batch: batch,
  27327. billboarding: billboarding,
  27328. bitAnd: bitAnd,
  27329. bitNot: bitNot,
  27330. bitOr: bitOr,
  27331. bitXor: bitXor,
  27332. bitangentGeometry: bitangentGeometry,
  27333. bitangentLocal: bitangentLocal,
  27334. bitangentView: bitangentView,
  27335. bitangentWorld: bitangentWorld,
  27336. bitcast: bitcast,
  27337. blendBurn: blendBurn,
  27338. blendColor: blendColor,
  27339. blendDodge: blendDodge,
  27340. blendOverlay: blendOverlay,
  27341. blendScreen: blendScreen,
  27342. blur: blur,
  27343. bool: bool,
  27344. buffer: buffer,
  27345. bufferAttribute: bufferAttribute,
  27346. bumpMap: bumpMap,
  27347. burn: burn,
  27348. bvec2: bvec2,
  27349. bvec3: bvec3,
  27350. bvec4: bvec4,
  27351. bypass: bypass,
  27352. cache: cache,
  27353. call: call,
  27354. cameraFar: cameraFar,
  27355. cameraIndex: cameraIndex,
  27356. cameraNear: cameraNear,
  27357. cameraNormalMatrix: cameraNormalMatrix,
  27358. cameraPosition: cameraPosition,
  27359. cameraProjectionMatrix: cameraProjectionMatrix,
  27360. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27361. cameraViewMatrix: cameraViewMatrix,
  27362. cameraWorldMatrix: cameraWorldMatrix,
  27363. cbrt: cbrt,
  27364. cdl: cdl,
  27365. ceil: ceil,
  27366. checker: checker,
  27367. cineonToneMapping: cineonToneMapping,
  27368. clamp: clamp,
  27369. clearcoat: clearcoat,
  27370. clearcoatRoughness: clearcoatRoughness,
  27371. code: code,
  27372. color: color,
  27373. colorSpaceToWorking: colorSpaceToWorking,
  27374. colorToDirection: colorToDirection,
  27375. compute: compute,
  27376. cond: cond,
  27377. context: context,
  27378. convert: convert,
  27379. convertColorSpace: convertColorSpace,
  27380. convertToTexture: convertToTexture,
  27381. cos: cos,
  27382. cross: cross,
  27383. cubeTexture: cubeTexture,
  27384. dFdx: dFdx,
  27385. dFdy: dFdy,
  27386. dashSize: dashSize,
  27387. defaultBuildStages: defaultBuildStages,
  27388. defaultShaderStages: defaultShaderStages,
  27389. defined: defined,
  27390. degrees: degrees,
  27391. deltaTime: deltaTime,
  27392. densityFog: densityFog,
  27393. densityFogFactor: densityFogFactor,
  27394. depth: depth,
  27395. depthPass: depthPass,
  27396. difference: difference,
  27397. diffuseColor: diffuseColor,
  27398. directPointLight: directPointLight,
  27399. directionToColor: directionToColor,
  27400. dispersion: dispersion,
  27401. distance: distance,
  27402. div: div,
  27403. dodge: dodge,
  27404. dot: dot,
  27405. drawIndex: drawIndex,
  27406. dynamicBufferAttribute: dynamicBufferAttribute,
  27407. element: element,
  27408. emissive: emissive,
  27409. equal: equal,
  27410. equals: equals,
  27411. equirectUV: equirectUV,
  27412. exp: exp,
  27413. exp2: exp2,
  27414. expression: expression,
  27415. faceDirection: faceDirection,
  27416. faceForward: faceForward,
  27417. faceforward: faceforward,
  27418. float: float,
  27419. floor: floor,
  27420. fog: fog,
  27421. fract: fract,
  27422. frameGroup: frameGroup,
  27423. frameId: frameId,
  27424. frontFacing: frontFacing,
  27425. fwidth: fwidth,
  27426. gain: gain,
  27427. gapSize: gapSize,
  27428. getConstNodeType: getConstNodeType,
  27429. getCurrentStack: getCurrentStack,
  27430. getDirection: getDirection,
  27431. getDistanceAttenuation: getDistanceAttenuation,
  27432. getGeometryRoughness: getGeometryRoughness,
  27433. getNormalFromDepth: getNormalFromDepth,
  27434. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27435. getRoughness: getRoughness,
  27436. getScreenPosition: getScreenPosition,
  27437. getShIrradianceAt: getShIrradianceAt,
  27438. getTextureIndex: getTextureIndex,
  27439. getViewPosition: getViewPosition,
  27440. globalId: globalId,
  27441. glsl: glsl,
  27442. glslFn: glslFn,
  27443. grayscale: grayscale,
  27444. greaterThan: greaterThan,
  27445. greaterThanEqual: greaterThanEqual,
  27446. hash: hash,
  27447. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27448. highpModelViewMatrix: highpModelViewMatrix,
  27449. hue: hue,
  27450. instance: instance,
  27451. instanceIndex: instanceIndex,
  27452. instancedArray: instancedArray,
  27453. instancedBufferAttribute: instancedBufferAttribute,
  27454. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27455. instancedMesh: instancedMesh,
  27456. int: int,
  27457. inverseSqrt: inverseSqrt,
  27458. inversesqrt: inversesqrt,
  27459. invocationLocalIndex: invocationLocalIndex,
  27460. invocationSubgroupIndex: invocationSubgroupIndex,
  27461. ior: ior,
  27462. iridescence: iridescence,
  27463. iridescenceIOR: iridescenceIOR,
  27464. iridescenceThickness: iridescenceThickness,
  27465. ivec2: ivec2,
  27466. ivec3: ivec3,
  27467. ivec4: ivec4,
  27468. js: js,
  27469. label: label,
  27470. length: length,
  27471. lengthSq: lengthSq,
  27472. lessThan: lessThan,
  27473. lessThanEqual: lessThanEqual,
  27474. lightPosition: lightPosition,
  27475. lightProjectionUV: lightProjectionUV,
  27476. lightShadowMatrix: lightShadowMatrix,
  27477. lightTargetDirection: lightTargetDirection,
  27478. lightTargetPosition: lightTargetPosition,
  27479. lightViewPosition: lightViewPosition,
  27480. lightingContext: lightingContext,
  27481. lights: lights,
  27482. linearDepth: linearDepth,
  27483. linearToneMapping: linearToneMapping,
  27484. localId: localId,
  27485. log: log,
  27486. log2: log2,
  27487. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27488. loop: loop,
  27489. luminance: luminance,
  27490. mat2: mat2,
  27491. mat3: mat3,
  27492. mat4: mat4,
  27493. matcapUV: matcapUV,
  27494. materialAO: materialAO,
  27495. materialAlphaTest: materialAlphaTest,
  27496. materialAnisotropy: materialAnisotropy,
  27497. materialAnisotropyVector: materialAnisotropyVector,
  27498. materialAttenuationColor: materialAttenuationColor,
  27499. materialAttenuationDistance: materialAttenuationDistance,
  27500. materialClearcoat: materialClearcoat,
  27501. materialClearcoatNormal: materialClearcoatNormal,
  27502. materialClearcoatRoughness: materialClearcoatRoughness,
  27503. materialColor: materialColor,
  27504. materialDispersion: materialDispersion,
  27505. materialEmissive: materialEmissive,
  27506. materialIOR: materialIOR,
  27507. materialIridescence: materialIridescence,
  27508. materialIridescenceIOR: materialIridescenceIOR,
  27509. materialIridescenceThickness: materialIridescenceThickness,
  27510. materialLightMap: materialLightMap,
  27511. materialLineDashOffset: materialLineDashOffset,
  27512. materialLineDashSize: materialLineDashSize,
  27513. materialLineGapSize: materialLineGapSize,
  27514. materialLineScale: materialLineScale,
  27515. materialLineWidth: materialLineWidth,
  27516. materialMetalness: materialMetalness,
  27517. materialNormal: materialNormal,
  27518. materialOpacity: materialOpacity,
  27519. materialPointSize: materialPointSize,
  27520. materialReference: materialReference,
  27521. materialReflectivity: materialReflectivity,
  27522. materialRefractionRatio: materialRefractionRatio,
  27523. materialRotation: materialRotation,
  27524. materialRoughness: materialRoughness,
  27525. materialSheen: materialSheen,
  27526. materialSheenRoughness: materialSheenRoughness,
  27527. materialShininess: materialShininess,
  27528. materialSpecular: materialSpecular,
  27529. materialSpecularColor: materialSpecularColor,
  27530. materialSpecularIntensity: materialSpecularIntensity,
  27531. materialSpecularStrength: materialSpecularStrength,
  27532. materialThickness: materialThickness,
  27533. materialTransmission: materialTransmission,
  27534. max: max$1,
  27535. maxMipLevel: maxMipLevel,
  27536. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27537. metalness: metalness,
  27538. min: min$1,
  27539. mix: mix,
  27540. mixElement: mixElement,
  27541. mod: mod,
  27542. modInt: modInt,
  27543. modelDirection: modelDirection,
  27544. modelNormalMatrix: modelNormalMatrix,
  27545. modelPosition: modelPosition,
  27546. modelScale: modelScale,
  27547. modelViewMatrix: modelViewMatrix,
  27548. modelViewPosition: modelViewPosition,
  27549. modelViewProjection: modelViewProjection,
  27550. modelWorldMatrix: modelWorldMatrix,
  27551. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27552. morphReference: morphReference,
  27553. mrt: mrt,
  27554. mul: mul,
  27555. mx_aastep: mx_aastep,
  27556. mx_cell_noise_float: mx_cell_noise_float,
  27557. mx_contrast: mx_contrast,
  27558. mx_fractal_noise_float: mx_fractal_noise_float,
  27559. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27560. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27561. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27562. mx_hsvtorgb: mx_hsvtorgb,
  27563. mx_noise_float: mx_noise_float,
  27564. mx_noise_vec3: mx_noise_vec3,
  27565. mx_noise_vec4: mx_noise_vec4,
  27566. mx_ramplr: mx_ramplr,
  27567. mx_ramptb: mx_ramptb,
  27568. mx_rgbtohsv: mx_rgbtohsv,
  27569. mx_safepower: mx_safepower,
  27570. mx_splitlr: mx_splitlr,
  27571. mx_splittb: mx_splittb,
  27572. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27573. mx_transform_uv: mx_transform_uv,
  27574. mx_worley_noise_float: mx_worley_noise_float,
  27575. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27576. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27577. negate: negate,
  27578. neutralToneMapping: neutralToneMapping,
  27579. nodeArray: nodeArray,
  27580. nodeImmutable: nodeImmutable,
  27581. nodeObject: nodeObject,
  27582. nodeObjects: nodeObjects,
  27583. nodeProxy: nodeProxy,
  27584. normalFlat: normalFlat,
  27585. normalGeometry: normalGeometry,
  27586. normalLocal: normalLocal,
  27587. normalMap: normalMap,
  27588. normalView: normalView,
  27589. normalWorld: normalWorld,
  27590. normalize: normalize,
  27591. not: not,
  27592. notEqual: notEqual,
  27593. numWorkgroups: numWorkgroups,
  27594. objectDirection: objectDirection,
  27595. objectGroup: objectGroup,
  27596. objectPosition: objectPosition,
  27597. objectScale: objectScale,
  27598. objectViewPosition: objectViewPosition,
  27599. objectWorldMatrix: objectWorldMatrix,
  27600. oneMinus: oneMinus,
  27601. or: or,
  27602. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27603. oscSawtooth: oscSawtooth,
  27604. oscSine: oscSine,
  27605. oscSquare: oscSquare,
  27606. oscTriangle: oscTriangle,
  27607. output: output,
  27608. outputStruct: outputStruct,
  27609. overlay: overlay,
  27610. overloadingFn: overloadingFn,
  27611. parabola: parabola,
  27612. parallaxDirection: parallaxDirection,
  27613. parallaxUV: parallaxUV,
  27614. parameter: parameter,
  27615. pass: pass,
  27616. passTexture: passTexture,
  27617. pcurve: pcurve,
  27618. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27619. pmremTexture: pmremTexture,
  27620. pointUV: pointUV,
  27621. pointWidth: pointWidth,
  27622. positionGeometry: positionGeometry,
  27623. positionLocal: positionLocal,
  27624. positionPrevious: positionPrevious,
  27625. positionView: positionView,
  27626. positionViewDirection: positionViewDirection,
  27627. positionWorld: positionWorld,
  27628. positionWorldDirection: positionWorldDirection,
  27629. posterize: posterize,
  27630. pow: pow,
  27631. pow2: pow2,
  27632. pow3: pow3,
  27633. pow4: pow4,
  27634. property: property,
  27635. radians: radians,
  27636. rand: rand,
  27637. range: range,
  27638. rangeFog: rangeFog,
  27639. rangeFogFactor: rangeFogFactor,
  27640. reciprocal: reciprocal,
  27641. reference: reference,
  27642. referenceBuffer: referenceBuffer,
  27643. reflect: reflect,
  27644. reflectVector: reflectVector,
  27645. reflectView: reflectView,
  27646. reflector: reflector,
  27647. refract: refract,
  27648. refractVector: refractVector,
  27649. refractView: refractView,
  27650. reinhardToneMapping: reinhardToneMapping,
  27651. remainder: remainder,
  27652. remap: remap,
  27653. remapClamp: remapClamp,
  27654. renderGroup: renderGroup,
  27655. renderOutput: renderOutput,
  27656. rendererReference: rendererReference,
  27657. rotate: rotate,
  27658. rotateUV: rotateUV,
  27659. roughness: roughness,
  27660. round: round,
  27661. rtt: rtt,
  27662. sRGBTransferEOTF: sRGBTransferEOTF,
  27663. sRGBTransferOETF: sRGBTransferOETF,
  27664. sampler: sampler,
  27665. saturate: saturate,
  27666. saturation: saturation,
  27667. screen: screen,
  27668. screenCoordinate: screenCoordinate,
  27669. screenSize: screenSize,
  27670. screenUV: screenUV,
  27671. scriptable: scriptable,
  27672. scriptableValue: scriptableValue,
  27673. select: select,
  27674. setCurrentStack: setCurrentStack,
  27675. shaderStages: shaderStages,
  27676. shadow: shadow,
  27677. shadowPositionWorld: shadowPositionWorld,
  27678. shapeCircle: shapeCircle,
  27679. sharedUniformGroup: sharedUniformGroup,
  27680. sheen: sheen,
  27681. sheenRoughness: sheenRoughness,
  27682. shiftLeft: shiftLeft,
  27683. shiftRight: shiftRight,
  27684. shininess: shininess,
  27685. sign: sign,
  27686. sin: sin,
  27687. sinc: sinc,
  27688. skinning: skinning,
  27689. skinningReference: skinningReference,
  27690. smoothstep: smoothstep,
  27691. smoothstepElement: smoothstepElement,
  27692. specularColor: specularColor,
  27693. specularF90: specularF90,
  27694. spherizeUV: spherizeUV,
  27695. split: split,
  27696. spritesheetUV: spritesheetUV,
  27697. sqrt: sqrt,
  27698. stack: stack,
  27699. step: step,
  27700. storage: storage,
  27701. storageBarrier: storageBarrier,
  27702. storageObject: storageObject,
  27703. storageTexture: storageTexture,
  27704. string: string,
  27705. sub: sub,
  27706. subgroupIndex: subgroupIndex,
  27707. subgroupSize: subgroupSize,
  27708. tan: tan,
  27709. tangentGeometry: tangentGeometry,
  27710. tangentLocal: tangentLocal,
  27711. tangentView: tangentView,
  27712. tangentWorld: tangentWorld,
  27713. temp: temp,
  27714. texture: texture,
  27715. texture3D: texture3D,
  27716. textureBarrier: textureBarrier,
  27717. textureBicubic: textureBicubic,
  27718. textureCubeUV: textureCubeUV,
  27719. textureLoad: textureLoad,
  27720. textureSize: textureSize,
  27721. textureStore: textureStore,
  27722. thickness: thickness,
  27723. time: time,
  27724. timerDelta: timerDelta,
  27725. timerGlobal: timerGlobal,
  27726. timerLocal: timerLocal,
  27727. toOutputColorSpace: toOutputColorSpace,
  27728. toWorkingColorSpace: toWorkingColorSpace,
  27729. toneMapping: toneMapping,
  27730. toneMappingExposure: toneMappingExposure,
  27731. toonOutlinePass: toonOutlinePass,
  27732. transformDirection: transformDirection,
  27733. transformNormal: transformNormal,
  27734. transformNormalToView: transformNormalToView,
  27735. transformedBentNormalView: transformedBentNormalView,
  27736. transformedBitangentView: transformedBitangentView,
  27737. transformedBitangentWorld: transformedBitangentWorld,
  27738. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27739. transformedNormalView: transformedNormalView,
  27740. transformedNormalWorld: transformedNormalWorld,
  27741. transformedTangentView: transformedTangentView,
  27742. transformedTangentWorld: transformedTangentWorld,
  27743. transmission: transmission,
  27744. transpose: transpose,
  27745. triNoise3D: triNoise3D,
  27746. triplanarTexture: triplanarTexture,
  27747. triplanarTextures: triplanarTextures,
  27748. trunc: trunc,
  27749. tslFn: tslFn,
  27750. uint: uint,
  27751. uniform: uniform,
  27752. uniformArray: uniformArray,
  27753. uniformGroup: uniformGroup,
  27754. uniforms: uniforms,
  27755. userData: userData,
  27756. uv: uv,
  27757. uvec2: uvec2,
  27758. uvec3: uvec3,
  27759. uvec4: uvec4,
  27760. varying: varying,
  27761. varyingProperty: varyingProperty,
  27762. vec2: vec2,
  27763. vec3: vec3,
  27764. vec4: vec4,
  27765. vectorComponents: vectorComponents,
  27766. velocity: velocity,
  27767. vertexColor: vertexColor,
  27768. vertexIndex: vertexIndex,
  27769. vertexStage: vertexStage,
  27770. vibrance: vibrance,
  27771. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27772. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27773. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27774. viewport: viewport,
  27775. viewportBottomLeft: viewportBottomLeft,
  27776. viewportCoordinate: viewportCoordinate,
  27777. viewportDepthTexture: viewportDepthTexture,
  27778. viewportLinearDepth: viewportLinearDepth,
  27779. viewportMipTexture: viewportMipTexture,
  27780. viewportResolution: viewportResolution,
  27781. viewportSafeUV: viewportSafeUV,
  27782. viewportSharedTexture: viewportSharedTexture,
  27783. viewportSize: viewportSize,
  27784. viewportTexture: viewportTexture,
  27785. viewportTopLeft: viewportTopLeft,
  27786. viewportUV: viewportUV,
  27787. wgsl: wgsl,
  27788. wgslFn: wgslFn,
  27789. workgroupArray: workgroupArray,
  27790. workgroupBarrier: workgroupBarrier,
  27791. workgroupId: workgroupId,
  27792. workingToColorSpace: workingToColorSpace,
  27793. xor: xor
  27794. });
  27795. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27796. /**
  27797. * This renderer module manages the background.
  27798. *
  27799. * @private
  27800. * @augments DataMap
  27801. */
  27802. class Background extends DataMap {
  27803. /**
  27804. * Constructs a new background management component.
  27805. *
  27806. * @param {Renderer} renderer - The renderer.
  27807. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27808. */
  27809. constructor( renderer, nodes ) {
  27810. super();
  27811. /**
  27812. * The renderer.
  27813. *
  27814. * @type {Renderer}
  27815. */
  27816. this.renderer = renderer;
  27817. /**
  27818. * Renderer component for managing nodes related logic.
  27819. *
  27820. * @type {Nodes}
  27821. */
  27822. this.nodes = nodes;
  27823. }
  27824. /**
  27825. * Updates the background for the given scene. Depending on how `Scene.background`
  27826. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27827. * or add a mesh to the render list for rendering the background as a textured plane
  27828. * or skybox.
  27829. *
  27830. * @param {Scene} scene - The scene.
  27831. * @param {RenderList} renderList - The current render list.
  27832. * @param {RenderContext} renderContext - The current render context.
  27833. */
  27834. update( scene, renderList, renderContext ) {
  27835. const renderer = this.renderer;
  27836. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27837. let forceClear = false;
  27838. if ( background === null ) {
  27839. // no background settings, use clear color configuration from the renderer
  27840. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27841. _clearColor$1.a = renderer._clearColor.a;
  27842. } else if ( background.isColor === true ) {
  27843. // background is an opaque color
  27844. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27845. _clearColor$1.a = 1;
  27846. forceClear = true;
  27847. } else if ( background.isNode === true ) {
  27848. const sceneData = this.get( scene );
  27849. const backgroundNode = background;
  27850. _clearColor$1.copy( renderer._clearColor );
  27851. let backgroundMesh = sceneData.backgroundMesh;
  27852. if ( backgroundMesh === undefined ) {
  27853. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27854. // @TODO: Add Texture2D support using node context
  27855. getUV: () => backgroundRotation.mul( normalWorld ),
  27856. getTextureLevel: () => backgroundBlurriness
  27857. } );
  27858. let viewProj = modelViewProjection;
  27859. viewProj = viewProj.setZ( viewProj.w );
  27860. const nodeMaterial = new NodeMaterial();
  27861. nodeMaterial.name = 'Background.material';
  27862. nodeMaterial.side = BackSide;
  27863. nodeMaterial.depthTest = false;
  27864. nodeMaterial.depthWrite = false;
  27865. nodeMaterial.fog = false;
  27866. nodeMaterial.lights = false;
  27867. nodeMaterial.vertexNode = viewProj;
  27868. nodeMaterial.colorNode = backgroundMeshNode;
  27869. sceneData.backgroundMeshNode = backgroundMeshNode;
  27870. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27871. backgroundMesh.frustumCulled = false;
  27872. backgroundMesh.name = 'Background.mesh';
  27873. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27874. this.matrixWorld.copyPosition( camera.matrixWorld );
  27875. };
  27876. }
  27877. const backgroundCacheKey = backgroundNode.getCacheKey();
  27878. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27879. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27880. sceneData.backgroundMeshNode.needsUpdate = true;
  27881. backgroundMesh.material.needsUpdate = true;
  27882. sceneData.backgroundCacheKey = backgroundCacheKey;
  27883. }
  27884. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27885. } else {
  27886. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27887. }
  27888. //
  27889. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  27890. if ( environmentBlendMode === 'additive' ) {
  27891. _clearColor$1.set( 0, 0, 0, 1 );
  27892. } else if ( environmentBlendMode === 'alpha-blend' ) {
  27893. _clearColor$1.set( 0, 0, 0, 0 );
  27894. }
  27895. //
  27896. if ( renderer.autoClear === true || forceClear === true ) {
  27897. const clearColorValue = renderContext.clearColorValue;
  27898. clearColorValue.r = _clearColor$1.r;
  27899. clearColorValue.g = _clearColor$1.g;
  27900. clearColorValue.b = _clearColor$1.b;
  27901. clearColorValue.a = _clearColor$1.a;
  27902. // premultiply alpha
  27903. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27904. clearColorValue.r *= clearColorValue.a;
  27905. clearColorValue.g *= clearColorValue.a;
  27906. clearColorValue.b *= clearColorValue.a;
  27907. }
  27908. //
  27909. renderContext.depthClearValue = renderer._clearDepth;
  27910. renderContext.stencilClearValue = renderer._clearStencil;
  27911. renderContext.clearColor = renderer.autoClearColor === true;
  27912. renderContext.clearDepth = renderer.autoClearDepth === true;
  27913. renderContext.clearStencil = renderer.autoClearStencil === true;
  27914. } else {
  27915. renderContext.clearColor = false;
  27916. renderContext.clearDepth = false;
  27917. renderContext.clearStencil = false;
  27918. }
  27919. }
  27920. }
  27921. let _id$6 = 0;
  27922. /**
  27923. * A bind group represents a collection of bindings and thus a collection
  27924. * or resources. Bind groups are assigned to pipelines to provide them
  27925. * with the required resources (like uniform buffers or textures).
  27926. *
  27927. * @private
  27928. */
  27929. class BindGroup {
  27930. /**
  27931. * Constructs a new bind group.
  27932. *
  27933. * @param {String} name - The bind group's name.
  27934. * @param {Array<Binding>} bindings - An array of bindings.
  27935. * @param {Number} index - The group index.
  27936. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27937. */
  27938. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27939. /**
  27940. * The bind group's name.
  27941. *
  27942. * @type {String}
  27943. */
  27944. this.name = name;
  27945. /**
  27946. * An array of bindings.
  27947. *
  27948. * @type {Array<Binding>}
  27949. */
  27950. this.bindings = bindings;
  27951. /**
  27952. * The group index.
  27953. *
  27954. * @type {Number}
  27955. */
  27956. this.index = index;
  27957. /**
  27958. * An array of reference bindings.
  27959. *
  27960. * @type {Array<Binding>}
  27961. */
  27962. this.bindingsReference = bindingsReference;
  27963. /**
  27964. * The group's ID.
  27965. *
  27966. * @type {Number}
  27967. */
  27968. this.id = _id$6 ++;
  27969. }
  27970. }
  27971. /**
  27972. * This module represents the state of a node builder after it was
  27973. * used to build the nodes for a render object. The state holds the
  27974. * results of the build for further processing in the renderer.
  27975. *
  27976. * Render objects with identical cache keys share the same node builder state.
  27977. *
  27978. * @private
  27979. */
  27980. class NodeBuilderState {
  27981. /**
  27982. * Constructs a new node builder state.
  27983. *
  27984. * @param {String?} vertexShader - The native vertex shader code.
  27985. * @param {String?} fragmentShader - The native fragment shader code.
  27986. * @param {String?} computeShader - The native compute shader code.
  27987. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27988. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27989. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27990. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27991. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27992. * @param {NodeMaterialObserver} observer - A node material observer.
  27993. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27994. */
  27995. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  27996. /**
  27997. * The native vertex shader code.
  27998. *
  27999. * @type {String}
  28000. */
  28001. this.vertexShader = vertexShader;
  28002. /**
  28003. * The native fragment shader code.
  28004. *
  28005. * @type {String}
  28006. */
  28007. this.fragmentShader = fragmentShader;
  28008. /**
  28009. * The native compute shader code.
  28010. *
  28011. * @type {String}
  28012. */
  28013. this.computeShader = computeShader;
  28014. /**
  28015. * An array with transform attribute objects.
  28016. * Only relevant when using compute shaders with WebGL 2.
  28017. *
  28018. * @type {Array<Object>}
  28019. */
  28020. this.transforms = transforms;
  28021. /**
  28022. * An array of node attributes representing
  28023. * the attributes of the shaders.
  28024. *
  28025. * @type {Array<NodeAttribute>}
  28026. */
  28027. this.nodeAttributes = nodeAttributes;
  28028. /**
  28029. * An array of bind groups representing the uniform or storage
  28030. * buffers, texture or samplers of the shader.
  28031. *
  28032. * @type {Array<BindGroup>}
  28033. */
  28034. this.bindings = bindings;
  28035. /**
  28036. * An array of nodes that implement their `update()` method.
  28037. *
  28038. * @type {Array<Node>}
  28039. */
  28040. this.updateNodes = updateNodes;
  28041. /**
  28042. * An array of nodes that implement their `updateBefore()` method.
  28043. *
  28044. * @type {Array<Node>}
  28045. */
  28046. this.updateBeforeNodes = updateBeforeNodes;
  28047. /**
  28048. * An array of nodes that implement their `updateAfter()` method.
  28049. *
  28050. * @type {Array<Node>}
  28051. */
  28052. this.updateAfterNodes = updateAfterNodes;
  28053. /**
  28054. * A node material observer.
  28055. *
  28056. * @type {NodeMaterialObserver}
  28057. */
  28058. this.observer = observer;
  28059. /**
  28060. * How often this state is used by render objects.
  28061. *
  28062. * @type {Number}
  28063. */
  28064. this.usedTimes = 0;
  28065. }
  28066. /**
  28067. * This method is used to create a array of bind groups based
  28068. * on the existing bind groups of this state. Shared groups are
  28069. * not cloned.
  28070. *
  28071. * @return {Array<BindGroup>} A array of bind groups.
  28072. */
  28073. createBindings() {
  28074. const bindings = [];
  28075. for ( const instanceGroup of this.bindings ) {
  28076. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28077. if ( shared !== true ) {
  28078. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28079. bindings.push( bindingsGroup );
  28080. for ( const instanceBinding of instanceGroup.bindings ) {
  28081. bindingsGroup.bindings.push( instanceBinding.clone() );
  28082. }
  28083. } else {
  28084. bindings.push( instanceGroup );
  28085. }
  28086. }
  28087. return bindings;
  28088. }
  28089. }
  28090. /**
  28091. * {@link NodeBuilder} is going to create instances of this class during the build process
  28092. * of nodes. They represent the final shader attributes that are going to be generated
  28093. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28094. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28095. */
  28096. class NodeAttribute {
  28097. /**
  28098. * Constructs a new node attribute.
  28099. *
  28100. * @param {String} name - The name of the attribute.
  28101. * @param {String} type - The type of the attribute.
  28102. * @param {Node?} node - An optional reference to the node.
  28103. */
  28104. constructor( name, type, node = null ) {
  28105. /**
  28106. * This flag can be used for type testing.
  28107. *
  28108. * @type {Boolean}
  28109. * @readonly
  28110. * @default true
  28111. */
  28112. this.isNodeAttribute = true;
  28113. /**
  28114. * The name of the attribute.
  28115. *
  28116. * @type {String}
  28117. */
  28118. this.name = name;
  28119. /**
  28120. * The type of the attribute.
  28121. *
  28122. * @type {String}
  28123. */
  28124. this.type = type;
  28125. /**
  28126. * An optional reference to the node.
  28127. *
  28128. * @type {Node?}
  28129. * @default null
  28130. */
  28131. this.node = node;
  28132. }
  28133. }
  28134. /**
  28135. * {@link NodeBuilder} is going to create instances of this class during the build process
  28136. * of nodes. They represent the final shader uniforms that are going to be generated
  28137. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28138. * for this purpose.
  28139. */
  28140. class NodeUniform {
  28141. /**
  28142. * Constructs a new node uniform.
  28143. *
  28144. * @param {String} name - The name of the uniform.
  28145. * @param {String} type - The type of the uniform.
  28146. * @param {UniformNode} node - An reference to the node.
  28147. */
  28148. constructor( name, type, node ) {
  28149. /**
  28150. * This flag can be used for type testing.
  28151. *
  28152. * @type {Boolean}
  28153. * @readonly
  28154. * @default true
  28155. */
  28156. this.isNodeUniform = true;
  28157. /**
  28158. * The name of the uniform.
  28159. *
  28160. * @type {String}
  28161. */
  28162. this.name = name;
  28163. /**
  28164. * The type of the uniform.
  28165. *
  28166. * @type {String}
  28167. */
  28168. this.type = type;
  28169. /**
  28170. * An reference to the node.
  28171. *
  28172. * @type {UniformNode}
  28173. */
  28174. this.node = node.getSelf();
  28175. }
  28176. /**
  28177. * The value of the uniform node.
  28178. *
  28179. * @type {Any}
  28180. */
  28181. get value() {
  28182. return this.node.value;
  28183. }
  28184. set value( val ) {
  28185. this.node.value = val;
  28186. }
  28187. /**
  28188. * The id of the uniform node.
  28189. *
  28190. * @type {Number}
  28191. */
  28192. get id() {
  28193. return this.node.id;
  28194. }
  28195. /**
  28196. * The uniform node's group.
  28197. *
  28198. * @type {UniformGroupNode}
  28199. */
  28200. get groupNode() {
  28201. return this.node.groupNode;
  28202. }
  28203. }
  28204. /**
  28205. * {@link NodeBuilder} is going to create instances of this class during the build process
  28206. * of nodes. They represent the final shader variables that are going to be generated
  28207. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28208. * this purpose.
  28209. */
  28210. class NodeVar {
  28211. /**
  28212. * Constructs a new node variable.
  28213. *
  28214. * @param {String} name - The name of the variable.
  28215. * @param {String} type - The type of the variable.
  28216. * @param {Boolean} [readOnly=false] - The read-only flag.
  28217. */
  28218. constructor( name, type, readOnly = false ) {
  28219. /**
  28220. * This flag can be used for type testing.
  28221. *
  28222. * @type {Boolean}
  28223. * @readonly
  28224. * @default true
  28225. */
  28226. this.isNodeVar = true;
  28227. /**
  28228. * The name of the variable.
  28229. *
  28230. * @type {String}
  28231. */
  28232. this.name = name;
  28233. /**
  28234. * The type of the variable.
  28235. *
  28236. * @type {String}
  28237. */
  28238. this.type = type;
  28239. /**
  28240. * The read-only flag.
  28241. *
  28242. * @type {boolean}
  28243. */
  28244. this.readOnly = readOnly;
  28245. }
  28246. }
  28247. /**
  28248. * {@link NodeBuilder} is going to create instances of this class during the build process
  28249. * of nodes. They represent the final shader varyings that are going to be generated
  28250. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28251. * this purpose.
  28252. *
  28253. * @augments NodeVar
  28254. */
  28255. class NodeVarying extends NodeVar {
  28256. /**
  28257. * Constructs a new node varying.
  28258. *
  28259. * @param {String} name - The name of the varying.
  28260. * @param {String} type - The type of the varying.
  28261. */
  28262. constructor( name, type ) {
  28263. super( name, type );
  28264. /**
  28265. * Whether this varying requires interpolation or not. This property can be used
  28266. * to check if the varying can be optimized for a variable.
  28267. *
  28268. * @type {Boolean}
  28269. * @default false
  28270. */
  28271. this.needsInterpolation = false;
  28272. /**
  28273. * This flag can be used for type testing.
  28274. *
  28275. * @type {Boolean}
  28276. * @readonly
  28277. * @default true
  28278. */
  28279. this.isNodeVarying = true;
  28280. }
  28281. }
  28282. /**
  28283. * {@link NodeBuilder} is going to create instances of this class during the build process
  28284. * of nodes. They represent user-defined, native shader code portions that are going to be
  28285. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28286. * for this purpose.
  28287. */
  28288. class NodeCode {
  28289. /**
  28290. * Constructs a new code node.
  28291. *
  28292. * @param {String} name - The name of the code.
  28293. * @param {String} type - The node type.
  28294. * @param {String} [code=''] - The native shader code.
  28295. */
  28296. constructor( name, type, code = '' ) {
  28297. /**
  28298. * The name of the code.
  28299. *
  28300. * @type {String}
  28301. */
  28302. this.name = name;
  28303. /**
  28304. * The node type.
  28305. *
  28306. * @type {String}
  28307. */
  28308. this.type = type;
  28309. /**
  28310. * The native shader code.
  28311. *
  28312. * @type {String}
  28313. * @default ''
  28314. */
  28315. this.code = code;
  28316. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28317. }
  28318. }
  28319. let _id$5 = 0;
  28320. /**
  28321. * This utility class is used in {@link NodeBuilder} as an internal
  28322. * cache data structure for node data.
  28323. */
  28324. class NodeCache {
  28325. /**
  28326. * Constructs a new node cache.
  28327. *
  28328. * @param {NodeCache?} parent - A reference to a parent cache.
  28329. */
  28330. constructor( parent = null ) {
  28331. /**
  28332. * The id of the cache.
  28333. *
  28334. * @type {Number}
  28335. * @readonly
  28336. */
  28337. this.id = _id$5 ++;
  28338. /**
  28339. * A weak map for managing node data.
  28340. *
  28341. * @type {WeakMap<Node, Object>}
  28342. */
  28343. this.nodesData = new WeakMap();
  28344. /**
  28345. * Reference to a parent node cache.
  28346. *
  28347. * @type {NodeCache?}
  28348. * @default null
  28349. */
  28350. this.parent = parent;
  28351. }
  28352. /**
  28353. * Returns the data for the given node.
  28354. *
  28355. * @param {Node} node - The node.
  28356. * @return {Object?} The data for the node.
  28357. */
  28358. getData( node ) {
  28359. let data = this.nodesData.get( node );
  28360. if ( data === undefined && this.parent !== null ) {
  28361. data = this.parent.getData( node );
  28362. }
  28363. return data;
  28364. }
  28365. /**
  28366. * Sets the data for a given node.
  28367. *
  28368. * @param {Node} node - The node.
  28369. * @param {Object} data - The data that should be cached.
  28370. */
  28371. setData( node, data ) {
  28372. this.nodesData.set( node, data );
  28373. }
  28374. }
  28375. /**
  28376. * {@link NodeBuilder} is going to create instances of this class during the build process
  28377. * of nodes. They represent the final shader struct data that are going to be generated
  28378. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28379. * for this purpose.
  28380. */
  28381. class StructTypeNode extends Node {
  28382. static get type() {
  28383. return 'StructTypeNode';
  28384. }
  28385. /**
  28386. * Constructs a new struct type node.
  28387. *
  28388. * @param {String} name - The name of the struct.
  28389. * @param {Array<String>} types - An array of types.
  28390. */
  28391. constructor( name, types ) {
  28392. super();
  28393. /**
  28394. * The name of the struct.
  28395. *
  28396. * @type {String}
  28397. */
  28398. this.name = name;
  28399. /**
  28400. * An array of types.
  28401. *
  28402. * @type {Array<String>}
  28403. */
  28404. this.types = types;
  28405. /**
  28406. * This flag can be used for type testing.
  28407. *
  28408. * @type {Boolean}
  28409. * @readonly
  28410. * @default true
  28411. */
  28412. this.isStructTypeNode = true;
  28413. }
  28414. /**
  28415. * Returns the member types.
  28416. *
  28417. * @return {Array<String>} The types.
  28418. */
  28419. getMemberTypes() {
  28420. return this.types;
  28421. }
  28422. }
  28423. /**
  28424. * Abstract base class for uniforms.
  28425. *
  28426. * @abstract
  28427. * @private
  28428. */
  28429. class Uniform {
  28430. /**
  28431. * Constructs a new uniform.
  28432. *
  28433. * @param {String} name - The uniform's name.
  28434. * @param {Any} value - The uniform's value.
  28435. */
  28436. constructor( name, value ) {
  28437. /**
  28438. * The uniform's name.
  28439. *
  28440. * @type {String}
  28441. */
  28442. this.name = name;
  28443. /**
  28444. * The uniform's value.
  28445. *
  28446. * @type {Any}
  28447. */
  28448. this.value = value;
  28449. /**
  28450. * Used to build the uniform buffer according to the STD140 layout.
  28451. * Derived uniforms will set this property to a data type specific
  28452. * value.
  28453. *
  28454. * @type {Number}
  28455. */
  28456. this.boundary = 0;
  28457. /**
  28458. * The item size. Derived uniforms will set this property to a data
  28459. * type specific value.
  28460. *
  28461. * @type {Number}
  28462. */
  28463. this.itemSize = 0;
  28464. /**
  28465. * This property is set by {@link UniformsGroup} and marks
  28466. * the start position in the uniform buffer.
  28467. *
  28468. * @type {Number}
  28469. */
  28470. this.offset = 0;
  28471. }
  28472. /**
  28473. * Sets the uniform's value.
  28474. *
  28475. * @param {Any} value - The value to set.
  28476. */
  28477. setValue( value ) {
  28478. this.value = value;
  28479. }
  28480. /**
  28481. * Returns the uniform's value.
  28482. *
  28483. * @return {Any} The value.
  28484. */
  28485. getValue() {
  28486. return this.value;
  28487. }
  28488. }
  28489. /**
  28490. * Represents a Number uniform.
  28491. *
  28492. * @private
  28493. * @augments Uniform
  28494. */
  28495. class NumberUniform extends Uniform {
  28496. /**
  28497. * Constructs a new Number uniform.
  28498. *
  28499. * @param {String} name - The uniform's name.
  28500. * @param {Number} value - The uniform's value.
  28501. */
  28502. constructor( name, value = 0 ) {
  28503. super( name, value );
  28504. /**
  28505. * This flag can be used for type testing.
  28506. *
  28507. * @type {Boolean}
  28508. * @readonly
  28509. * @default true
  28510. */
  28511. this.isNumberUniform = true;
  28512. this.boundary = 4;
  28513. this.itemSize = 1;
  28514. }
  28515. }
  28516. /**
  28517. * Represents a Vector2 uniform.
  28518. *
  28519. * @private
  28520. * @augments Uniform
  28521. */
  28522. class Vector2Uniform extends Uniform {
  28523. /**
  28524. * Constructs a new Number uniform.
  28525. *
  28526. * @param {String} name - The uniform's name.
  28527. * @param {Vector2} value - The uniform's value.
  28528. */
  28529. constructor( name, value = new Vector2() ) {
  28530. super( name, value );
  28531. /**
  28532. * This flag can be used for type testing.
  28533. *
  28534. * @type {Boolean}
  28535. * @readonly
  28536. * @default true
  28537. */
  28538. this.isVector2Uniform = true;
  28539. this.boundary = 8;
  28540. this.itemSize = 2;
  28541. }
  28542. }
  28543. /**
  28544. * Represents a Vector3 uniform.
  28545. *
  28546. * @private
  28547. * @augments Uniform
  28548. */
  28549. class Vector3Uniform extends Uniform {
  28550. /**
  28551. * Constructs a new Number uniform.
  28552. *
  28553. * @param {String} name - The uniform's name.
  28554. * @param {Vector3} value - The uniform's value.
  28555. */
  28556. constructor( name, value = new Vector3() ) {
  28557. super( name, value );
  28558. /**
  28559. * This flag can be used for type testing.
  28560. *
  28561. * @type {Boolean}
  28562. * @readonly
  28563. * @default true
  28564. */
  28565. this.isVector3Uniform = true;
  28566. this.boundary = 16;
  28567. this.itemSize = 3;
  28568. }
  28569. }
  28570. /**
  28571. * Represents a Vector4 uniform.
  28572. *
  28573. * @private
  28574. * @augments Uniform
  28575. */
  28576. class Vector4Uniform extends Uniform {
  28577. /**
  28578. * Constructs a new Number uniform.
  28579. *
  28580. * @param {String} name - The uniform's name.
  28581. * @param {Vector4} value - The uniform's value.
  28582. */
  28583. constructor( name, value = new Vector4() ) {
  28584. super( name, value );
  28585. /**
  28586. * This flag can be used for type testing.
  28587. *
  28588. * @type {Boolean}
  28589. * @readonly
  28590. * @default true
  28591. */
  28592. this.isVector4Uniform = true;
  28593. this.boundary = 16;
  28594. this.itemSize = 4;
  28595. }
  28596. }
  28597. /**
  28598. * Represents a Color uniform.
  28599. *
  28600. * @private
  28601. * @augments Uniform
  28602. */
  28603. class ColorUniform extends Uniform {
  28604. /**
  28605. * Constructs a new Number uniform.
  28606. *
  28607. * @param {String} name - The uniform's name.
  28608. * @param {Color} value - The uniform's value.
  28609. */
  28610. constructor( name, value = new Color() ) {
  28611. super( name, value );
  28612. /**
  28613. * This flag can be used for type testing.
  28614. *
  28615. * @type {Boolean}
  28616. * @readonly
  28617. * @default true
  28618. */
  28619. this.isColorUniform = true;
  28620. this.boundary = 16;
  28621. this.itemSize = 3;
  28622. }
  28623. }
  28624. /**
  28625. * Represents a Matrix3 uniform.
  28626. *
  28627. * @private
  28628. * @augments Uniform
  28629. */
  28630. class Matrix3Uniform extends Uniform {
  28631. /**
  28632. * Constructs a new Number uniform.
  28633. *
  28634. * @param {String} name - The uniform's name.
  28635. * @param {Matrix3} value - The uniform's value.
  28636. */
  28637. constructor( name, value = new Matrix3() ) {
  28638. super( name, value );
  28639. /**
  28640. * This flag can be used for type testing.
  28641. *
  28642. * @type {Boolean}
  28643. * @readonly
  28644. * @default true
  28645. */
  28646. this.isMatrix3Uniform = true;
  28647. this.boundary = 48;
  28648. this.itemSize = 12;
  28649. }
  28650. }
  28651. /**
  28652. * Represents a Matrix4 uniform.
  28653. *
  28654. * @private
  28655. * @augments Uniform
  28656. */
  28657. class Matrix4Uniform extends Uniform {
  28658. /**
  28659. * Constructs a new Number uniform.
  28660. *
  28661. * @param {String} name - The uniform's name.
  28662. * @param {Matrix4} value - The uniform's value.
  28663. */
  28664. constructor( name, value = new Matrix4() ) {
  28665. super( name, value );
  28666. /**
  28667. * This flag can be used for type testing.
  28668. *
  28669. * @type {Boolean}
  28670. * @readonly
  28671. * @default true
  28672. */
  28673. this.isMatrix4Uniform = true;
  28674. this.boundary = 64;
  28675. this.itemSize = 16;
  28676. }
  28677. }
  28678. /**
  28679. * A special form of Number uniform binding type.
  28680. * It's value is managed by a node object.
  28681. *
  28682. * @private
  28683. * @augments NumberUniform
  28684. */
  28685. class NumberNodeUniform extends NumberUniform {
  28686. /**
  28687. * Constructs a new node-based Number uniform.
  28688. *
  28689. * @param {NodeUniform} nodeUniform - The node uniform.
  28690. */
  28691. constructor( nodeUniform ) {
  28692. super( nodeUniform.name, nodeUniform.value );
  28693. /**
  28694. * The node uniform.
  28695. *
  28696. * @type {NodeUniform}
  28697. */
  28698. this.nodeUniform = nodeUniform;
  28699. }
  28700. /**
  28701. * Overwritten to return the value of the node uniform.
  28702. *
  28703. * @return {Number} The value.
  28704. */
  28705. getValue() {
  28706. return this.nodeUniform.value;
  28707. }
  28708. /**
  28709. * Returns the node uniform data type.
  28710. *
  28711. * @return {String} The data type.
  28712. */
  28713. getType() {
  28714. return this.nodeUniform.type;
  28715. }
  28716. }
  28717. /**
  28718. * A special form of Vector2 uniform binding type.
  28719. * It's value is managed by a node object.
  28720. *
  28721. * @private
  28722. * @augments Vector2Uniform
  28723. */
  28724. class Vector2NodeUniform extends Vector2Uniform {
  28725. /**
  28726. * Constructs a new node-based Vector2 uniform.
  28727. *
  28728. * @param {NodeUniform} nodeUniform - The node uniform.
  28729. */
  28730. constructor( nodeUniform ) {
  28731. super( nodeUniform.name, nodeUniform.value );
  28732. /**
  28733. * The node uniform.
  28734. *
  28735. * @type {NodeUniform}
  28736. */
  28737. this.nodeUniform = nodeUniform;
  28738. }
  28739. /**
  28740. * Overwritten to return the value of the node uniform.
  28741. *
  28742. * @return {Vector2} The value.
  28743. */
  28744. getValue() {
  28745. return this.nodeUniform.value;
  28746. }
  28747. /**
  28748. * Returns the node uniform data type.
  28749. *
  28750. * @return {String} The data type.
  28751. */
  28752. getType() {
  28753. return this.nodeUniform.type;
  28754. }
  28755. }
  28756. /**
  28757. * A special form of Vector3 uniform binding type.
  28758. * It's value is managed by a node object.
  28759. *
  28760. * @private
  28761. * @augments Vector3Uniform
  28762. */
  28763. class Vector3NodeUniform extends Vector3Uniform {
  28764. /**
  28765. * Constructs a new node-based Vector3 uniform.
  28766. *
  28767. * @param {NodeUniform} nodeUniform - The node uniform.
  28768. */
  28769. constructor( nodeUniform ) {
  28770. super( nodeUniform.name, nodeUniform.value );
  28771. /**
  28772. * The node uniform.
  28773. *
  28774. * @type {NodeUniform}
  28775. */
  28776. this.nodeUniform = nodeUniform;
  28777. }
  28778. /**
  28779. * Overwritten to return the value of the node uniform.
  28780. *
  28781. * @return {Vector3} The value.
  28782. */
  28783. getValue() {
  28784. return this.nodeUniform.value;
  28785. }
  28786. /**
  28787. * Returns the node uniform data type.
  28788. *
  28789. * @return {String} The data type.
  28790. */
  28791. getType() {
  28792. return this.nodeUniform.type;
  28793. }
  28794. }
  28795. /**
  28796. * A special form of Vector4 uniform binding type.
  28797. * It's value is managed by a node object.
  28798. *
  28799. * @private
  28800. * @augments Vector4Uniform
  28801. */
  28802. class Vector4NodeUniform extends Vector4Uniform {
  28803. /**
  28804. * Constructs a new node-based Vector4 uniform.
  28805. *
  28806. * @param {NodeUniform} nodeUniform - The node uniform.
  28807. */
  28808. constructor( nodeUniform ) {
  28809. super( nodeUniform.name, nodeUniform.value );
  28810. /**
  28811. * The node uniform.
  28812. *
  28813. * @type {NodeUniform}
  28814. */
  28815. this.nodeUniform = nodeUniform;
  28816. }
  28817. /**
  28818. * Overwritten to return the value of the node uniform.
  28819. *
  28820. * @return {Vector4} The value.
  28821. */
  28822. getValue() {
  28823. return this.nodeUniform.value;
  28824. }
  28825. /**
  28826. * Returns the node uniform data type.
  28827. *
  28828. * @return {String} The data type.
  28829. */
  28830. getType() {
  28831. return this.nodeUniform.type;
  28832. }
  28833. }
  28834. /**
  28835. * A special form of Color uniform binding type.
  28836. * It's value is managed by a node object.
  28837. *
  28838. * @private
  28839. * @augments ColorUniform
  28840. */
  28841. class ColorNodeUniform extends ColorUniform {
  28842. /**
  28843. * Constructs a new node-based Color uniform.
  28844. *
  28845. * @param {NodeUniform} nodeUniform - The node uniform.
  28846. */
  28847. constructor( nodeUniform ) {
  28848. super( nodeUniform.name, nodeUniform.value );
  28849. /**
  28850. * The node uniform.
  28851. *
  28852. * @type {NodeUniform}
  28853. */
  28854. this.nodeUniform = nodeUniform;
  28855. }
  28856. /**
  28857. * Overwritten to return the value of the node uniform.
  28858. *
  28859. * @return {Color} The value.
  28860. */
  28861. getValue() {
  28862. return this.nodeUniform.value;
  28863. }
  28864. /**
  28865. * Returns the node uniform data type.
  28866. *
  28867. * @return {String} The data type.
  28868. */
  28869. getType() {
  28870. return this.nodeUniform.type;
  28871. }
  28872. }
  28873. /**
  28874. * A special form of Matrix3 uniform binding type.
  28875. * It's value is managed by a node object.
  28876. *
  28877. * @private
  28878. * @augments Matrix3Uniform
  28879. */
  28880. class Matrix3NodeUniform extends Matrix3Uniform {
  28881. /**
  28882. * Constructs a new node-based Matrix3 uniform.
  28883. *
  28884. * @param {NodeUniform} nodeUniform - The node uniform.
  28885. */
  28886. constructor( nodeUniform ) {
  28887. super( nodeUniform.name, nodeUniform.value );
  28888. /**
  28889. * The node uniform.
  28890. *
  28891. * @type {NodeUniform}
  28892. */
  28893. this.nodeUniform = nodeUniform;
  28894. }
  28895. /**
  28896. * Overwritten to return the value of the node uniform.
  28897. *
  28898. * @return {Matrix3} The value.
  28899. */
  28900. getValue() {
  28901. return this.nodeUniform.value;
  28902. }
  28903. /**
  28904. * Returns the node uniform data type.
  28905. *
  28906. * @return {String} The data type.
  28907. */
  28908. getType() {
  28909. return this.nodeUniform.type;
  28910. }
  28911. }
  28912. /**
  28913. * A special form of Matrix4 uniform binding type.
  28914. * It's value is managed by a node object.
  28915. *
  28916. * @private
  28917. * @augments Matrix4Uniform
  28918. */
  28919. class Matrix4NodeUniform extends Matrix4Uniform {
  28920. /**
  28921. * Constructs a new node-based Matrix4 uniform.
  28922. *
  28923. * @param {NodeUniform} nodeUniform - The node uniform.
  28924. */
  28925. constructor( nodeUniform ) {
  28926. super( nodeUniform.name, nodeUniform.value );
  28927. /**
  28928. * The node uniform.
  28929. *
  28930. * @type {NodeUniform}
  28931. */
  28932. this.nodeUniform = nodeUniform;
  28933. }
  28934. /**
  28935. * Overwritten to return the value of the node uniform.
  28936. *
  28937. * @return {Matrix4} The value.
  28938. */
  28939. getValue() {
  28940. return this.nodeUniform.value;
  28941. }
  28942. /**
  28943. * Returns the node uniform data type.
  28944. *
  28945. * @return {String} The data type.
  28946. */
  28947. getType() {
  28948. return this.nodeUniform.type;
  28949. }
  28950. }
  28951. const LOD_MIN = 4;
  28952. // The standard deviations (radians) associated with the extra mips. These are
  28953. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28954. // geometric shadowing function. These sigma values squared must match the
  28955. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28956. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28957. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28958. // samples and exit early, but not recompile the shader.
  28959. const MAX_SAMPLES = 20;
  28960. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  28961. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28962. const _clearColor = /*@__PURE__*/ new Color();
  28963. let _oldTarget = null;
  28964. let _oldActiveCubeFace = 0;
  28965. let _oldActiveMipmapLevel = 0;
  28966. // Golden Ratio
  28967. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28968. const INV_PHI = 1 / PHI;
  28969. // Vertices of a dodecahedron (except the opposites, which represent the
  28970. // same axis), used as axis directions evenly spread on a sphere.
  28971. const _axisDirections = [
  28972. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28973. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28974. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28975. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28976. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28977. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28978. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  28979. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  28980. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  28981. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28982. ];
  28983. // maps blur materials to their uniforms dictionary
  28984. const _uniformsMap = new WeakMap();
  28985. // WebGPU Face indices
  28986. const _faceLib = [
  28987. 3, 1, 5,
  28988. 0, 4, 2
  28989. ];
  28990. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28991. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  28992. /**
  28993. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28994. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28995. * blur to be quickly accessed based on material roughness. It is packed into a
  28996. * special CubeUV format that allows us to perform custom interpolation so that
  28997. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28998. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28999. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29000. * higher roughness levels. In this way we maintain resolution to smoothly
  29001. * interpolate diffuse lighting while limiting sampling computation.
  29002. *
  29003. * Paper: Fast, Accurate Image-Based Lighting
  29004. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  29005. */
  29006. class PMREMGenerator {
  29007. constructor( renderer ) {
  29008. this._renderer = renderer;
  29009. this._pingPongRenderTarget = null;
  29010. this._lodMax = 0;
  29011. this._cubeSize = 0;
  29012. this._lodPlanes = [];
  29013. this._sizeLods = [];
  29014. this._sigmas = [];
  29015. this._lodMeshes = [];
  29016. this._blurMaterial = null;
  29017. this._cubemapMaterial = null;
  29018. this._equirectMaterial = null;
  29019. this._backgroundBox = null;
  29020. }
  29021. get _hasInitialized() {
  29022. return this._renderer.hasInitialized();
  29023. }
  29024. /**
  29025. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29026. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29027. * in radians to be applied to the scene before PMREM generation. Optional near
  29028. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29029. * is placed at the origin).
  29030. *
  29031. * @param {Scene} scene - The scene to be captured.
  29032. * @param {Number} [sigma=0] - The blur radius in radians.
  29033. * @param {Number} [near=0.1] - The near plane distance.
  29034. * @param {Number} [far=100] - The far plane distance.
  29035. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29036. * @return {RenderTarget} The resulting PMREM.
  29037. * @see fromSceneAsync
  29038. */
  29039. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29040. this._setSize( 256 );
  29041. if ( this._hasInitialized === false ) {
  29042. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29043. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29044. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29045. return cubeUVRenderTarget;
  29046. }
  29047. _oldTarget = this._renderer.getRenderTarget();
  29048. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29049. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29050. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29051. cubeUVRenderTarget.depthBuffer = true;
  29052. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29053. if ( sigma > 0 ) {
  29054. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29055. }
  29056. this._applyPMREM( cubeUVRenderTarget );
  29057. this._cleanup( cubeUVRenderTarget );
  29058. return cubeUVRenderTarget;
  29059. }
  29060. /**
  29061. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29062. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29063. * in radians to be applied to the scene before PMREM generation. Optional near
  29064. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29065. * is placed at the origin).
  29066. *
  29067. * @param {Scene} scene - The scene to be captured.
  29068. * @param {Number} [sigma=0] - The blur radius in radians.
  29069. * @param {Number} [near=0.1] - The near plane distance.
  29070. * @param {Number} [far=100] - The far plane distance.
  29071. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29072. * @return {Promise<RenderTarget>} The resulting PMREM.
  29073. * @see fromScene
  29074. */
  29075. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29076. if ( this._hasInitialized === false ) await this._renderer.init();
  29077. return this.fromScene( scene, sigma, near, far, renderTarget );
  29078. }
  29079. /**
  29080. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29081. * or HDR. The ideal input image size is 1k (1024 x 512),
  29082. * as this matches best with the 256 x 256 cubemap output.
  29083. *
  29084. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29085. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29086. * @return {RenderTarget} The resulting PMREM.
  29087. * @see fromEquirectangularAsync
  29088. */
  29089. fromEquirectangular( equirectangular, renderTarget = null ) {
  29090. if ( this._hasInitialized === false ) {
  29091. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29092. this._setSizeFromTexture( equirectangular );
  29093. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29094. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29095. return cubeUVRenderTarget;
  29096. }
  29097. return this._fromTexture( equirectangular, renderTarget );
  29098. }
  29099. /**
  29100. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29101. * or HDR. The ideal input image size is 1k (1024 x 512),
  29102. * as this matches best with the 256 x 256 cubemap output.
  29103. *
  29104. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29105. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29106. * @return {Promise<RenderTarget>} The resulting PMREM.
  29107. * @see fromEquirectangular
  29108. */
  29109. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29110. if ( this._hasInitialized === false ) await this._renderer.init();
  29111. return this._fromTexture( equirectangular, renderTarget );
  29112. }
  29113. /**
  29114. * Generates a PMREM from an cubemap texture, which can be either LDR
  29115. * or HDR. The ideal input cube size is 256 x 256,
  29116. * as this matches best with the 256 x 256 cubemap output.
  29117. *
  29118. * @param {Texture} cubemap - The cubemap texture to be converted.
  29119. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29120. * @return {RenderTarget} The resulting PMREM.
  29121. * @see fromCubemapAsync
  29122. */
  29123. fromCubemap( cubemap, renderTarget = null ) {
  29124. if ( this._hasInitialized === false ) {
  29125. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29126. this._setSizeFromTexture( cubemap );
  29127. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29128. this.fromCubemapAsync( cubemap, renderTarget );
  29129. return cubeUVRenderTarget;
  29130. }
  29131. return this._fromTexture( cubemap, renderTarget );
  29132. }
  29133. /**
  29134. * Generates a PMREM from an cubemap texture, which can be either LDR
  29135. * or HDR. The ideal input cube size is 256 x 256,
  29136. * with the 256 x 256 cubemap output.
  29137. *
  29138. * @param {Texture} cubemap - The cubemap texture to be converted.
  29139. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29140. * @return {Promise<RenderTarget>} The resulting PMREM.
  29141. * @see fromCubemap
  29142. */
  29143. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29144. if ( this._hasInitialized === false ) await this._renderer.init();
  29145. return this._fromTexture( cubemap, renderTarget );
  29146. }
  29147. /**
  29148. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29149. * your texture's network fetch for increased concurrency.
  29150. *
  29151. * @returns {Promise}
  29152. */
  29153. async compileCubemapShader() {
  29154. if ( this._cubemapMaterial === null ) {
  29155. this._cubemapMaterial = _getCubemapMaterial();
  29156. await this._compileMaterial( this._cubemapMaterial );
  29157. }
  29158. }
  29159. /**
  29160. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29161. * your texture's network fetch for increased concurrency.
  29162. *
  29163. * @returns {Promise}
  29164. */
  29165. async compileEquirectangularShader() {
  29166. if ( this._equirectMaterial === null ) {
  29167. this._equirectMaterial = _getEquirectMaterial();
  29168. await this._compileMaterial( this._equirectMaterial );
  29169. }
  29170. }
  29171. /**
  29172. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29173. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29174. * one of them will cause any others to also become unusable.
  29175. */
  29176. dispose() {
  29177. this._dispose();
  29178. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29179. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29180. if ( this._backgroundBox !== null ) {
  29181. this._backgroundBox.geometry.dispose();
  29182. this._backgroundBox.material.dispose();
  29183. }
  29184. }
  29185. // private interface
  29186. _setSizeFromTexture( texture ) {
  29187. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29188. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29189. } else { // Equirectangular
  29190. this._setSize( texture.image.width / 4 );
  29191. }
  29192. }
  29193. _setSize( cubeSize ) {
  29194. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29195. this._cubeSize = Math.pow( 2, this._lodMax );
  29196. }
  29197. _dispose() {
  29198. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29199. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29200. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29201. this._lodPlanes[ i ].dispose();
  29202. }
  29203. }
  29204. _cleanup( outputTarget ) {
  29205. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29206. outputTarget.scissorTest = false;
  29207. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29208. }
  29209. _fromTexture( texture, renderTarget ) {
  29210. this._setSizeFromTexture( texture );
  29211. _oldTarget = this._renderer.getRenderTarget();
  29212. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29213. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29214. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29215. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29216. this._applyPMREM( cubeUVRenderTarget );
  29217. this._cleanup( cubeUVRenderTarget );
  29218. return cubeUVRenderTarget;
  29219. }
  29220. _allocateTargets() {
  29221. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29222. const height = 4 * this._cubeSize;
  29223. const params = {
  29224. magFilter: LinearFilter,
  29225. minFilter: LinearFilter,
  29226. generateMipmaps: false,
  29227. type: HalfFloatType,
  29228. format: RGBAFormat,
  29229. colorSpace: LinearSRGBColorSpace,
  29230. //depthBuffer: false
  29231. };
  29232. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29233. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29234. if ( this._pingPongRenderTarget !== null ) {
  29235. this._dispose();
  29236. }
  29237. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29238. const { _lodMax } = this;
  29239. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29240. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29241. }
  29242. return cubeUVRenderTarget;
  29243. }
  29244. async _compileMaterial( material ) {
  29245. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29246. await this._renderer.compile( tmpMesh, _flatCamera );
  29247. }
  29248. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29249. const cubeCamera = _cubeCamera;
  29250. cubeCamera.near = near;
  29251. cubeCamera.far = far;
  29252. // px, py, pz, nx, ny, nz
  29253. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  29254. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  29255. const renderer = this._renderer;
  29256. const originalAutoClear = renderer.autoClear;
  29257. renderer.getClearColor( _clearColor );
  29258. renderer.autoClear = false;
  29259. let backgroundBox = this._backgroundBox;
  29260. if ( backgroundBox === null ) {
  29261. const backgroundMaterial = new MeshBasicMaterial( {
  29262. name: 'PMREM.Background',
  29263. side: BackSide,
  29264. depthWrite: false,
  29265. depthTest: false
  29266. } );
  29267. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29268. }
  29269. let useSolidColor = false;
  29270. const background = scene.background;
  29271. if ( background ) {
  29272. if ( background.isColor ) {
  29273. backgroundBox.material.color.copy( background );
  29274. scene.background = null;
  29275. useSolidColor = true;
  29276. }
  29277. } else {
  29278. backgroundBox.material.color.copy( _clearColor );
  29279. useSolidColor = true;
  29280. }
  29281. renderer.setRenderTarget( cubeUVRenderTarget );
  29282. renderer.clear();
  29283. if ( useSolidColor ) {
  29284. renderer.render( backgroundBox, cubeCamera );
  29285. }
  29286. for ( let i = 0; i < 6; i ++ ) {
  29287. const col = i % 3;
  29288. if ( col === 0 ) {
  29289. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29290. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29291. } else if ( col === 1 ) {
  29292. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29293. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29294. } else {
  29295. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29296. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29297. }
  29298. const size = this._cubeSize;
  29299. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29300. renderer.render( scene, cubeCamera );
  29301. }
  29302. renderer.autoClear = originalAutoClear;
  29303. scene.background = background;
  29304. }
  29305. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29306. const renderer = this._renderer;
  29307. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29308. if ( isCubeTexture ) {
  29309. if ( this._cubemapMaterial === null ) {
  29310. this._cubemapMaterial = _getCubemapMaterial( texture );
  29311. }
  29312. } else {
  29313. if ( this._equirectMaterial === null ) {
  29314. this._equirectMaterial = _getEquirectMaterial( texture );
  29315. }
  29316. }
  29317. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29318. material.fragmentNode.value = texture;
  29319. const mesh = this._lodMeshes[ 0 ];
  29320. mesh.material = material;
  29321. const size = this._cubeSize;
  29322. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29323. renderer.setRenderTarget( cubeUVRenderTarget );
  29324. renderer.render( mesh, _flatCamera );
  29325. }
  29326. _applyPMREM( cubeUVRenderTarget ) {
  29327. const renderer = this._renderer;
  29328. const autoClear = renderer.autoClear;
  29329. renderer.autoClear = false;
  29330. const n = this._lodPlanes.length;
  29331. for ( let i = 1; i < n; i ++ ) {
  29332. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29333. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29334. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29335. }
  29336. renderer.autoClear = autoClear;
  29337. }
  29338. /**
  29339. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29340. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29341. * the blur latitudinally (around the poles), and then longitudinally (towards
  29342. * the poles) to approximate the orthogonally-separable blur. It is least
  29343. * accurate at the poles, but still does a decent job.
  29344. *
  29345. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29346. * @param {Number} lodIn - The input level-of-detail.
  29347. * @param {Number} lodOut - The output level-of-detail.
  29348. * @param {Number} sigma - The blur radius in radians.
  29349. * @param {Vector3} [poleAxis] - The pole axis.
  29350. */
  29351. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29352. const pingPongRenderTarget = this._pingPongRenderTarget;
  29353. this._halfBlur(
  29354. cubeUVRenderTarget,
  29355. pingPongRenderTarget,
  29356. lodIn,
  29357. lodOut,
  29358. sigma,
  29359. 'latitudinal',
  29360. poleAxis );
  29361. this._halfBlur(
  29362. pingPongRenderTarget,
  29363. cubeUVRenderTarget,
  29364. lodOut,
  29365. lodOut,
  29366. sigma,
  29367. 'longitudinal',
  29368. poleAxis );
  29369. }
  29370. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29371. const renderer = this._renderer;
  29372. const blurMaterial = this._blurMaterial;
  29373. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29374. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29375. }
  29376. // Number of standard deviations at which to cut off the discrete approximation.
  29377. const STANDARD_DEVIATIONS = 3;
  29378. const blurMesh = this._lodMeshes[ lodOut ];
  29379. blurMesh.material = blurMaterial;
  29380. const blurUniforms = _uniformsMap.get( blurMaterial );
  29381. const pixels = this._sizeLods[ lodIn ] - 1;
  29382. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29383. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29384. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29385. if ( samples > MAX_SAMPLES ) {
  29386. console.warn( `sigmaRadians, ${
  29387. sigmaRadians}, is too large and will clip, as it requested ${
  29388. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29389. }
  29390. const weights = [];
  29391. let sum = 0;
  29392. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29393. const x = i / sigmaPixels;
  29394. const weight = Math.exp( - x * x / 2 );
  29395. weights.push( weight );
  29396. if ( i === 0 ) {
  29397. sum += weight;
  29398. } else if ( i < samples ) {
  29399. sum += 2 * weight;
  29400. }
  29401. }
  29402. for ( let i = 0; i < weights.length; i ++ ) {
  29403. weights[ i ] = weights[ i ] / sum;
  29404. }
  29405. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29406. blurUniforms.envMap.value = targetIn.texture;
  29407. blurUniforms.samples.value = samples;
  29408. blurUniforms.weights.array = weights;
  29409. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29410. if ( poleAxis ) {
  29411. blurUniforms.poleAxis.value = poleAxis;
  29412. }
  29413. const { _lodMax } = this;
  29414. blurUniforms.dTheta.value = radiansPerPixel;
  29415. blurUniforms.mipInt.value = _lodMax - lodIn;
  29416. const outputSize = this._sizeLods[ lodOut ];
  29417. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29418. const y = 4 * ( this._cubeSize - outputSize );
  29419. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29420. renderer.setRenderTarget( targetOut );
  29421. renderer.render( blurMesh, _flatCamera );
  29422. }
  29423. }
  29424. function _createPlanes( lodMax ) {
  29425. const lodPlanes = [];
  29426. const sizeLods = [];
  29427. const sigmas = [];
  29428. const lodMeshes = [];
  29429. let lod = lodMax;
  29430. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29431. for ( let i = 0; i < totalLods; i ++ ) {
  29432. const sizeLod = Math.pow( 2, lod );
  29433. sizeLods.push( sizeLod );
  29434. let sigma = 1.0 / sizeLod;
  29435. if ( i > lodMax - LOD_MIN ) {
  29436. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29437. } else if ( i === 0 ) {
  29438. sigma = 0;
  29439. }
  29440. sigmas.push( sigma );
  29441. const texelSize = 1.0 / ( sizeLod - 2 );
  29442. const min = - texelSize;
  29443. const max = 1 + texelSize;
  29444. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29445. const cubeFaces = 6;
  29446. const vertices = 6;
  29447. const positionSize = 3;
  29448. const uvSize = 2;
  29449. const faceIndexSize = 1;
  29450. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29451. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29452. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29453. for ( let face = 0; face < cubeFaces; face ++ ) {
  29454. const x = ( face % 3 ) * 2 / 3 - 1;
  29455. const y = face > 2 ? 0 : -1;
  29456. const coordinates = [
  29457. x, y, 0,
  29458. x + 2 / 3, y, 0,
  29459. x + 2 / 3, y + 1, 0,
  29460. x, y, 0,
  29461. x + 2 / 3, y + 1, 0,
  29462. x, y + 1, 0
  29463. ];
  29464. const faceIdx = _faceLib[ face ];
  29465. position.set( coordinates, positionSize * vertices * faceIdx );
  29466. uv.set( uv1, uvSize * vertices * faceIdx );
  29467. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29468. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29469. }
  29470. const planes = new BufferGeometry();
  29471. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29472. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29473. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29474. lodPlanes.push( planes );
  29475. lodMeshes.push( new Mesh( planes, null ) );
  29476. if ( lod > LOD_MIN ) {
  29477. lod --;
  29478. }
  29479. }
  29480. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29481. }
  29482. function _createRenderTarget( width, height, params ) {
  29483. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29484. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29485. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29486. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29487. cubeUVRenderTarget.scissorTest = true;
  29488. return cubeUVRenderTarget;
  29489. }
  29490. function _setViewport( target, x, y, width, height ) {
  29491. target.viewport.set( x, y, width, height );
  29492. target.scissor.set( x, y, width, height );
  29493. }
  29494. function _getMaterial( type ) {
  29495. const material = new NodeMaterial();
  29496. material.depthTest = false;
  29497. material.depthWrite = false;
  29498. material.blending = NoBlending;
  29499. material.name = `PMREM_${ type }`;
  29500. return material;
  29501. }
  29502. function _getBlurShader( lodMax, width, height ) {
  29503. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29504. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29505. const dTheta = uniform( 0 );
  29506. const n = float( MAX_SAMPLES );
  29507. const latitudinal = uniform( 0 ); // false, bool
  29508. const samples = uniform( 1 ); // int
  29509. const envMap = texture( null );
  29510. const mipInt = uniform( 0 ); // int
  29511. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29512. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29513. const CUBEUV_MAX_MIP = float( lodMax );
  29514. const materialUniforms = {
  29515. n,
  29516. latitudinal,
  29517. weights,
  29518. poleAxis,
  29519. outputDirection: _outputDirection,
  29520. dTheta,
  29521. samples,
  29522. envMap,
  29523. mipInt,
  29524. CUBEUV_TEXEL_WIDTH,
  29525. CUBEUV_TEXEL_HEIGHT,
  29526. CUBEUV_MAX_MIP
  29527. };
  29528. const material = _getMaterial( 'blur' );
  29529. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29530. _uniformsMap.set( material, materialUniforms );
  29531. return material;
  29532. }
  29533. function _getCubemapMaterial( envTexture ) {
  29534. const material = _getMaterial( 'cubemap' );
  29535. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29536. return material;
  29537. }
  29538. function _getEquirectMaterial( envTexture ) {
  29539. const material = _getMaterial( 'equirect' );
  29540. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29541. return material;
  29542. }
  29543. const rendererCache = new WeakMap();
  29544. const typeFromArray = new Map( [
  29545. [ Int8Array, 'int' ],
  29546. [ Int16Array, 'int' ],
  29547. [ Int32Array, 'int' ],
  29548. [ Uint8Array, 'uint' ],
  29549. [ Uint16Array, 'uint' ],
  29550. [ Uint32Array, 'uint' ],
  29551. [ Float32Array, 'float' ]
  29552. ] );
  29553. const toFloat = ( value ) => {
  29554. if ( /e/g.test( value ) ) {
  29555. return String( value ).replace( /\+/g, '' );
  29556. } else {
  29557. value = Number( value );
  29558. return value + ( value % 1 ? '' : '.0' );
  29559. }
  29560. };
  29561. /**
  29562. * Base class for builders which generate a shader program based
  29563. * on a 3D object and its node material definition.
  29564. */
  29565. class NodeBuilder {
  29566. /**
  29567. * Constructs a new node builder.
  29568. *
  29569. * @param {Object3D} object - The 3D object.
  29570. * @param {Renderer} renderer - The current renderer.
  29571. * @param {NodeParser} parser - A reference to a node parser.
  29572. */
  29573. constructor( object, renderer, parser ) {
  29574. /**
  29575. * The 3D object.
  29576. *
  29577. * @type {Object3D}
  29578. */
  29579. this.object = object;
  29580. /**
  29581. * The material of the 3D object.
  29582. *
  29583. * @type {Material?}
  29584. */
  29585. this.material = ( object && object.material ) || null;
  29586. /**
  29587. * The geometry of the 3D object.
  29588. *
  29589. * @type {BufferGeometry?}
  29590. */
  29591. this.geometry = ( object && object.geometry ) || null;
  29592. /**
  29593. * The current renderer.
  29594. *
  29595. * @type {Renderer}
  29596. */
  29597. this.renderer = renderer;
  29598. /**
  29599. * A reference to a node parser.
  29600. *
  29601. * @type {NodeParser}
  29602. */
  29603. this.parser = parser;
  29604. /**
  29605. * The scene the 3D object belongs to.
  29606. *
  29607. * @type {Scene?}
  29608. * @default null
  29609. */
  29610. this.scene = null;
  29611. /**
  29612. * The camera the 3D object is rendered with.
  29613. *
  29614. * @type {Camera?}
  29615. * @default null
  29616. */
  29617. this.camera = null;
  29618. /**
  29619. * A list of all nodes the builder is processing
  29620. * for this 3D object.
  29621. *
  29622. * @type {Array<Node>}
  29623. */
  29624. this.nodes = [];
  29625. /**
  29626. * A list of all sequential nodes.
  29627. *
  29628. * @type {Array<Node>}
  29629. */
  29630. this.sequentialNodes = [];
  29631. /**
  29632. * A list of all nodes which {@link Node#update} method should be executed.
  29633. *
  29634. * @type {Array<Node>}
  29635. */
  29636. this.updateNodes = [];
  29637. /**
  29638. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29639. *
  29640. * @type {Array<Node>}
  29641. */
  29642. this.updateBeforeNodes = [];
  29643. /**
  29644. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29645. *
  29646. * @type {Array<Node>}
  29647. */
  29648. this.updateAfterNodes = [];
  29649. /**
  29650. * A dictionary that assigns each node to a unique hash.
  29651. *
  29652. * @type {Object<Number,Node>}
  29653. */
  29654. this.hashNodes = {};
  29655. /**
  29656. * A reference to a node material observer.
  29657. *
  29658. * @type {NodeMaterialObserver?}
  29659. * @default null
  29660. */
  29661. this.observer = null;
  29662. /**
  29663. * A reference to the current lights node.
  29664. *
  29665. * @type {LightsNode?}
  29666. * @default null
  29667. */
  29668. this.lightsNode = null;
  29669. /**
  29670. * A reference to the current environment node.
  29671. *
  29672. * @type {Node?}
  29673. * @default null
  29674. */
  29675. this.environmentNode = null;
  29676. /**
  29677. * A reference to the current fog node.
  29678. *
  29679. * @type {FogNode?}
  29680. * @default null
  29681. */
  29682. this.fogNode = null;
  29683. /**
  29684. * The current clipping context.
  29685. *
  29686. * @type {ClippingContext?}
  29687. */
  29688. this.clippingContext = null;
  29689. /**
  29690. * The generated vertex shader.
  29691. *
  29692. * @type {String?}
  29693. */
  29694. this.vertexShader = null;
  29695. /**
  29696. * The generated fragment shader.
  29697. *
  29698. * @type {String?}
  29699. */
  29700. this.fragmentShader = null;
  29701. /**
  29702. * The generated compute shader.
  29703. *
  29704. * @type {String?}
  29705. */
  29706. this.computeShader = null;
  29707. /**
  29708. * Nodes used in the primary flow of code generation.
  29709. *
  29710. * @type {Object<String,Array<Node>>}
  29711. */
  29712. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29713. /**
  29714. * Nodes code from `.flowNodes`.
  29715. *
  29716. * @type {Object<String,String>}
  29717. */
  29718. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29719. /**
  29720. * This dictionary holds the node uniforms of the builder.
  29721. * The uniforms are maintained in an array for each shader stage.
  29722. *
  29723. * @type {Object}
  29724. */
  29725. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29726. /**
  29727. * This dictionary holds the output structs of the builder.
  29728. * The structs are maintained in an array for each shader stage.
  29729. *
  29730. * @type {Object}
  29731. */
  29732. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29733. /**
  29734. * This dictionary holds the bindings for each shader stage.
  29735. *
  29736. * @type {Object}
  29737. */
  29738. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29739. /**
  29740. * This dictionary maintains the binding indices per bind group.
  29741. *
  29742. * @type {Object}
  29743. */
  29744. this.bindingsIndexes = {};
  29745. /**
  29746. * Reference to the array of bind groups.
  29747. *
  29748. * @type {Array<BindGroup>?}
  29749. */
  29750. this.bindGroups = null;
  29751. /**
  29752. * This array holds the node attributes of this builder
  29753. * created via {@link AttributeNode}.
  29754. *
  29755. * @type {Array<NodeAttribute>}
  29756. */
  29757. this.attributes = [];
  29758. /**
  29759. * This array holds the node attributes of this builder
  29760. * created via {@link BufferAttributeNode}.
  29761. *
  29762. * @type {Array<NodeAttribute>}
  29763. */
  29764. this.bufferAttributes = [];
  29765. /**
  29766. * This array holds the node varyings of this builder.
  29767. *
  29768. * @type {Array<NodeVarying>}
  29769. */
  29770. this.varyings = [];
  29771. /**
  29772. * This dictionary holds the (native) node codes of this builder.
  29773. * The codes are maintained in an array for each shader stage.
  29774. *
  29775. * @type {Object<String,Array<NodeCode>>}
  29776. */
  29777. this.codes = {};
  29778. /**
  29779. * This dictionary holds the node variables of this builder.
  29780. * The variables are maintained in an array for each shader stage.
  29781. *
  29782. * @type {Object<String,Array<NodeVar>>}
  29783. */
  29784. this.vars = {};
  29785. /**
  29786. * Current code flow.
  29787. * All code generated in this stack will be stored in `.flow`.
  29788. *
  29789. * @type {{code: String}}
  29790. */
  29791. this.flow = { code: '' };
  29792. /**
  29793. * A chain of nodes.
  29794. * Used to check recursive calls in node-graph.
  29795. *
  29796. * @type {Array<Node>}
  29797. */
  29798. this.chaining = [];
  29799. /**
  29800. * The current stack.
  29801. * This reflects the current process in the code block hierarchy,
  29802. * it is useful to know if the current process is inside a conditional for example.
  29803. *
  29804. * @type {StackNode}
  29805. */
  29806. this.stack = stack();
  29807. /**
  29808. * List of stack nodes.
  29809. * The current stack hierarchy is stored in an array.
  29810. *
  29811. * @type {Array<StackNode>}
  29812. */
  29813. this.stacks = [];
  29814. /**
  29815. * A tab value. Used for shader string generation.
  29816. *
  29817. * @type {String}
  29818. * @default '\t'
  29819. */
  29820. this.tab = '\t';
  29821. /**
  29822. * Reference to the current function node.
  29823. *
  29824. * @type {FunctionNode?}
  29825. * @default null
  29826. */
  29827. this.currentFunctionNode = null;
  29828. /**
  29829. * The builder's context.
  29830. *
  29831. * @type {Object}
  29832. */
  29833. this.context = {
  29834. material: this.material
  29835. };
  29836. /**
  29837. * The builder's cache.
  29838. *
  29839. * @type {NodeCache}
  29840. */
  29841. this.cache = new NodeCache();
  29842. /**
  29843. * Since the {@link NodeBuilder#cache} might be temporarily
  29844. * overwritten by other caches, this member retains the reference
  29845. * to the builder's own cache.
  29846. *
  29847. * @type {NodeCache}
  29848. * @default this.cache
  29849. */
  29850. this.globalCache = this.cache;
  29851. this.flowsData = new WeakMap();
  29852. /**
  29853. * The current shader stage.
  29854. *
  29855. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29856. */
  29857. this.shaderStage = null;
  29858. /**
  29859. * The current build stage.
  29860. *
  29861. * @type {('setup'|'analyze'|'generate')?}
  29862. */
  29863. this.buildStage = null;
  29864. /**
  29865. * Whether comparison in shader code are generated with methods or not.
  29866. *
  29867. * @type {Boolean}
  29868. * @default false
  29869. */
  29870. this.useComparisonMethod = false;
  29871. }
  29872. /**
  29873. * Returns the bind groups of the current renderer.
  29874. *
  29875. * @return {ChainMap} The cache.
  29876. */
  29877. getBindGroupsCache() {
  29878. let bindGroupsCache = rendererCache.get( this.renderer );
  29879. if ( bindGroupsCache === undefined ) {
  29880. bindGroupsCache = new ChainMap();
  29881. rendererCache.set( this.renderer, bindGroupsCache );
  29882. }
  29883. return bindGroupsCache;
  29884. }
  29885. /**
  29886. * Factory method for creating an instance of {@link RenderTarget} with the given
  29887. * dimensions and options.
  29888. *
  29889. * @param {Number} width - The width of the render target.
  29890. * @param {Number} height - The height of the render target.
  29891. * @param {Object} options - The options of the render target.
  29892. * @return {RenderTarget} The render target.
  29893. */
  29894. createRenderTarget( width, height, options ) {
  29895. return new RenderTarget( width, height, options );
  29896. }
  29897. /**
  29898. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29899. * dimensions and options.
  29900. *
  29901. * @param {Number} size - The size of the cube render target.
  29902. * @param {Object} options - The options of the cube render target.
  29903. * @return {CubeRenderTarget} The cube render target.
  29904. */
  29905. createCubeRenderTarget( size, options ) {
  29906. return new CubeRenderTarget( size, options );
  29907. }
  29908. /**
  29909. * Factory method for creating an instance of {@link PMREMGenerator}.
  29910. *
  29911. * @return {PMREMGenerator} The PMREM generator.
  29912. */
  29913. createPMREMGenerator() {
  29914. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29915. return new PMREMGenerator( this.renderer );
  29916. }
  29917. /**
  29918. * Whether the given node is included in the internal array of nodes or not.
  29919. *
  29920. * @param {Node} node - The node to test.
  29921. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29922. */
  29923. includes( node ) {
  29924. return this.nodes.includes( node );
  29925. }
  29926. /**
  29927. * Returns the output struct name which is required by
  29928. * {@link module:OutputStructNode}.
  29929. *
  29930. * @abstract
  29931. * @return {String} The name of the output struct.
  29932. */
  29933. getOutputStructName() {}
  29934. /**
  29935. * Returns a bind group for the given group name and binding.
  29936. *
  29937. * @private
  29938. * @param {String} groupName - The group name.
  29939. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29940. * @return {BindGroup} The bind group
  29941. */
  29942. _getBindGroup( groupName, bindings ) {
  29943. const bindGroupsCache = this.getBindGroupsCache();
  29944. //
  29945. const bindingsArray = [];
  29946. let sharedGroup = true;
  29947. for ( const binding of bindings ) {
  29948. bindingsArray.push( binding );
  29949. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29950. }
  29951. //
  29952. let bindGroup;
  29953. if ( sharedGroup ) {
  29954. bindGroup = bindGroupsCache.get( bindingsArray );
  29955. if ( bindGroup === undefined ) {
  29956. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29957. bindGroupsCache.set( bindingsArray, bindGroup );
  29958. }
  29959. } else {
  29960. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29961. }
  29962. return bindGroup;
  29963. }
  29964. /**
  29965. * Returns an array of node uniform groups for the given group name and shader stage.
  29966. *
  29967. * @param {String} groupName - The group name.
  29968. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29969. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29970. */
  29971. getBindGroupArray( groupName, shaderStage ) {
  29972. const bindings = this.bindings[ shaderStage ];
  29973. let bindGroup = bindings[ groupName ];
  29974. if ( bindGroup === undefined ) {
  29975. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29976. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29977. }
  29978. bindings[ groupName ] = bindGroup = [];
  29979. }
  29980. return bindGroup;
  29981. }
  29982. /**
  29983. * Returns a list bindings of all shader stages separated by groups.
  29984. *
  29985. * @return {Array<BindGroup>} The list of bindings.
  29986. */
  29987. getBindings() {
  29988. let bindingsGroups = this.bindGroups;
  29989. if ( bindingsGroups === null ) {
  29990. const groups = {};
  29991. const bindings = this.bindings;
  29992. for ( const shaderStage of shaderStages ) {
  29993. for ( const groupName in bindings[ shaderStage ] ) {
  29994. const uniforms = bindings[ shaderStage ][ groupName ];
  29995. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29996. groupUniforms.push( ...uniforms );
  29997. }
  29998. }
  29999. bindingsGroups = [];
  30000. for ( const groupName in groups ) {
  30001. const group = groups[ groupName ];
  30002. const bindingsGroup = this._getBindGroup( groupName, group );
  30003. bindingsGroups.push( bindingsGroup );
  30004. }
  30005. this.bindGroups = bindingsGroups;
  30006. }
  30007. return bindingsGroups;
  30008. }
  30009. /**
  30010. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30011. */
  30012. sortBindingGroups() {
  30013. const bindingsGroups = this.getBindings();
  30014. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30015. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30016. const bindingGroup = bindingsGroups[ i ];
  30017. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30018. bindingGroup.index = i;
  30019. }
  30020. }
  30021. /**
  30022. * The builder maintains each node in a hash-based dictionary.
  30023. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30024. *
  30025. * @param {Node} node - The node to add.
  30026. * @param {Number} hash - The hash of the node.
  30027. */
  30028. setHashNode( node, hash ) {
  30029. this.hashNodes[ hash ] = node;
  30030. }
  30031. /**
  30032. * Adds a node to this builder.
  30033. *
  30034. * @param {Node} node - The node to add.
  30035. */
  30036. addNode( node ) {
  30037. if ( this.nodes.includes( node ) === false ) {
  30038. this.nodes.push( node );
  30039. this.setHashNode( node, node.getHash( this ) );
  30040. }
  30041. }
  30042. /**
  30043. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30044. * and need to follow a certain sequence in the calls to work correctly.
  30045. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30046. *
  30047. * @param {Node} node - The node to add.
  30048. */
  30049. addSequentialNode( node ) {
  30050. if ( this.sequentialNodes.includes( node ) === false ) {
  30051. this.sequentialNodes.push( node );
  30052. }
  30053. }
  30054. /**
  30055. * Checks the update types of nodes
  30056. */
  30057. buildUpdateNodes() {
  30058. for ( const node of this.nodes ) {
  30059. const updateType = node.getUpdateType();
  30060. if ( updateType !== NodeUpdateType.NONE ) {
  30061. this.updateNodes.push( node.getSelf() );
  30062. }
  30063. }
  30064. for ( const node of this.sequentialNodes ) {
  30065. const updateBeforeType = node.getUpdateBeforeType();
  30066. const updateAfterType = node.getUpdateAfterType();
  30067. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30068. this.updateBeforeNodes.push( node.getSelf() );
  30069. }
  30070. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30071. this.updateAfterNodes.push( node.getSelf() );
  30072. }
  30073. }
  30074. }
  30075. /**
  30076. * A reference the current node which is the
  30077. * last node in the chain of nodes.
  30078. *
  30079. * @type {Node}
  30080. */
  30081. get currentNode() {
  30082. return this.chaining[ this.chaining.length - 1 ];
  30083. }
  30084. /**
  30085. * Whether the given texture is filtered or not.
  30086. *
  30087. * @param {Texture} texture - The texture to check.
  30088. * @return {Boolean} Whether the given texture is filtered or not.
  30089. */
  30090. isFilteredTexture( texture ) {
  30091. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30092. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30093. }
  30094. /**
  30095. * Adds the given node to the internal node chain.
  30096. * This is used to check recursive calls in node-graph.
  30097. *
  30098. * @param {Node} node - The node to add.
  30099. */
  30100. addChain( node ) {
  30101. /*
  30102. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30103. console.warn( 'Recursive node: ', node );
  30104. }
  30105. */
  30106. this.chaining.push( node );
  30107. }
  30108. /**
  30109. * Removes the given node from the internal node chain.
  30110. *
  30111. * @param {Node} node - The node to remove.
  30112. */
  30113. removeChain( node ) {
  30114. const lastChain = this.chaining.pop();
  30115. if ( lastChain !== node ) {
  30116. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30117. }
  30118. }
  30119. /**
  30120. * Returns the native shader method name for a given generic name. E.g.
  30121. * the method name `textureDimensions` matches the WGSL name but must be
  30122. * resolved to `textureSize` in GLSL.
  30123. *
  30124. * @abstract
  30125. * @param {String} method - The method name to resolve.
  30126. * @return {String} The resolved method name.
  30127. */
  30128. getMethod( method ) {
  30129. return method;
  30130. }
  30131. /**
  30132. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30133. *
  30134. * @param {Number} hash - The hash of the node.
  30135. * @return {Node} The found node.
  30136. */
  30137. getNodeFromHash( hash ) {
  30138. return this.hashNodes[ hash ];
  30139. }
  30140. /**
  30141. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30142. *
  30143. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30144. * @param {Node} node - The node to add.
  30145. * @return {Node} The node.
  30146. */
  30147. addFlow( shaderStage, node ) {
  30148. this.flowNodes[ shaderStage ].push( node );
  30149. return node;
  30150. }
  30151. /**
  30152. * Sets builder's context.
  30153. *
  30154. * @param {Object} context - The context to set.
  30155. */
  30156. setContext( context ) {
  30157. this.context = context;
  30158. }
  30159. /**
  30160. * Returns the builder's current context.
  30161. *
  30162. * @return {Object} The builder's current context.
  30163. */
  30164. getContext() {
  30165. return this.context;
  30166. }
  30167. /**
  30168. * Gets a context used in shader construction that can be shared across different materials.
  30169. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30170. *
  30171. * @return {Object} The builder's current context without material.
  30172. */
  30173. getSharedContext() {
  30174. ({ ...this.context });
  30175. return this.context;
  30176. }
  30177. /**
  30178. * Sets builder's cache.
  30179. *
  30180. * @param {NodeCache} cache - The cache to set.
  30181. */
  30182. setCache( cache ) {
  30183. this.cache = cache;
  30184. }
  30185. /**
  30186. * Returns the builder's current cache.
  30187. *
  30188. * @return {NodeCache} The builder's current cache.
  30189. */
  30190. getCache() {
  30191. return this.cache;
  30192. }
  30193. /**
  30194. * Returns a cache for the given node.
  30195. *
  30196. * @param {Node} node - The node.
  30197. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30198. * @return {NodeCache} The cache.
  30199. */
  30200. getCacheFromNode( node, parent = true ) {
  30201. const data = this.getDataFromNode( node );
  30202. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30203. return data.cache;
  30204. }
  30205. /**
  30206. * Whether the requested feature is available or not.
  30207. *
  30208. * @abstract
  30209. * @param {String} name - The requested feature.
  30210. * @return {Boolean} Whether the requested feature is supported or not.
  30211. */
  30212. isAvailable( /*name*/ ) {
  30213. return false;
  30214. }
  30215. /**
  30216. * Returns the vertexIndex input variable as a native shader string.
  30217. *
  30218. * @abstract
  30219. * @return {String} The instanceIndex shader string.
  30220. */
  30221. getVertexIndex() {
  30222. console.warn( 'Abstract function.' );
  30223. }
  30224. /**
  30225. * Returns the instanceIndex input variable as a native shader string.
  30226. *
  30227. * @abstract
  30228. * @return {String} The instanceIndex shader string.
  30229. */
  30230. getInstanceIndex() {
  30231. console.warn( 'Abstract function.' );
  30232. }
  30233. /**
  30234. * Returns the drawIndex input variable as a native shader string.
  30235. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30236. *
  30237. * @abstract
  30238. * @return {String} The drawIndex shader string.
  30239. */
  30240. getDrawIndex() {
  30241. console.warn( 'Abstract function.' );
  30242. }
  30243. /**
  30244. * Returns the frontFacing input variable as a native shader string.
  30245. *
  30246. * @abstract
  30247. * @return {String} The frontFacing shader string.
  30248. */
  30249. getFrontFacing() {
  30250. console.warn( 'Abstract function.' );
  30251. }
  30252. /**
  30253. * Returns the fragCoord input variable as a native shader string.
  30254. *
  30255. * @abstract
  30256. * @return {String} The fragCoord shader string.
  30257. */
  30258. getFragCoord() {
  30259. console.warn( 'Abstract function.' );
  30260. }
  30261. /**
  30262. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30263. * this method evaluate to `true`, WebGPU to `false`.
  30264. *
  30265. * @abstract
  30266. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30267. */
  30268. isFlipY() {
  30269. return false;
  30270. }
  30271. /**
  30272. * Calling this method increases the usage count for the given node by one.
  30273. *
  30274. * @param {Node} node - The node to increase the usage count for.
  30275. * @return {Number} The updated usage count.
  30276. */
  30277. increaseUsage( node ) {
  30278. const nodeData = this.getDataFromNode( node );
  30279. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30280. return nodeData.usageCount;
  30281. }
  30282. /**
  30283. * Generates a texture sample shader string for the given texture data.
  30284. *
  30285. * @abstract
  30286. * @param {Texture} texture - The texture.
  30287. * @param {String} textureProperty - The texture property name.
  30288. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30289. * @return {String} The generated shader string.
  30290. */
  30291. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30292. console.warn( 'Abstract function.' );
  30293. }
  30294. /**
  30295. * Generates a texture LOD shader string for the given texture data.
  30296. *
  30297. * @abstract
  30298. * @param {Texture} texture - The texture.
  30299. * @param {String} textureProperty - The texture property name.
  30300. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30301. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30302. * @param {String} levelSnippet - Snippet defining the mip level.
  30303. * @return {String} The generated shader string.
  30304. */
  30305. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30306. console.warn( 'Abstract function.' );
  30307. }
  30308. /**
  30309. * Generates the shader string for the given type and value.
  30310. *
  30311. * @param {String} type - The type.
  30312. * @param {Any?} [value=null] - The value.
  30313. * @return {String} The generated value as a shader string.
  30314. */
  30315. generateConst( type, value = null ) {
  30316. if ( value === null ) {
  30317. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30318. else if ( type === 'bool' ) value = false;
  30319. else if ( type === 'color' ) value = new Color();
  30320. else if ( type === 'vec2' ) value = new Vector2();
  30321. else if ( type === 'vec3' ) value = new Vector3();
  30322. else if ( type === 'vec4' ) value = new Vector4();
  30323. }
  30324. if ( type === 'float' ) return toFloat( value );
  30325. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30326. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30327. if ( type === 'bool' ) return value ? 'true' : 'false';
  30328. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30329. const typeLength = this.getTypeLength( type );
  30330. const componentType = this.getComponentType( type );
  30331. const generateConst = value => this.generateConst( componentType, value );
  30332. if ( typeLength === 2 ) {
  30333. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30334. } else if ( typeLength === 3 ) {
  30335. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30336. } else if ( typeLength === 4 ) {
  30337. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30338. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30339. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30340. } else if ( typeLength > 4 ) {
  30341. return `${ this.getType( type ) }()`;
  30342. }
  30343. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30344. }
  30345. /**
  30346. * It might be necessary to convert certain data types to different ones
  30347. * so this method can be used to hide the conversion.
  30348. *
  30349. * @param {String} type - The type.
  30350. * @return {String} The updated type.
  30351. */
  30352. getType( type ) {
  30353. if ( type === 'color' ) return 'vec3';
  30354. return type;
  30355. }
  30356. /**
  30357. * Whether the given attribute name is defined in the geometry or not.
  30358. *
  30359. * @param {String} name - The attribute name.
  30360. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30361. */
  30362. hasGeometryAttribute( name ) {
  30363. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30364. }
  30365. /**
  30366. * Returns a node attribute for the given name and type.
  30367. *
  30368. * @param {String} name - The attribute's name.
  30369. * @param {String} type - The attribute's type.
  30370. * @return {NodeAttribute} The node attribute.
  30371. */
  30372. getAttribute( name, type ) {
  30373. const attributes = this.attributes;
  30374. // find attribute
  30375. for ( const attribute of attributes ) {
  30376. if ( attribute.name === name ) {
  30377. return attribute;
  30378. }
  30379. }
  30380. // create a new if no exist
  30381. const attribute = new NodeAttribute( name, type );
  30382. attributes.push( attribute );
  30383. return attribute;
  30384. }
  30385. /**
  30386. * Returns for the given node and shader stage the property name for the shader.
  30387. *
  30388. * @param {Node} node - The node.
  30389. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30390. * @return {String} The property name.
  30391. */
  30392. getPropertyName( node/*, shaderStage*/ ) {
  30393. return node.name;
  30394. }
  30395. /**
  30396. * Whether the given type is a vector type or not.
  30397. *
  30398. * @param {String} type - The type to check.
  30399. * @return {Boolean} Whether the given type is a vector type or not.
  30400. */
  30401. isVector( type ) {
  30402. return /vec\d/.test( type );
  30403. }
  30404. /**
  30405. * Whether the given type is a matrix type or not.
  30406. *
  30407. * @param {String} type - The type to check.
  30408. * @return {Boolean} Whether the given type is a matrix type or not.
  30409. */
  30410. isMatrix( type ) {
  30411. return /mat\d/.test( type );
  30412. }
  30413. /**
  30414. * Whether the given type is a reference type or not.
  30415. *
  30416. * @param {String} type - The type to check.
  30417. * @return {Boolean} Whether the given type is a reference type or not.
  30418. */
  30419. isReference( type ) {
  30420. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30421. }
  30422. /**
  30423. * Checks if the given texture requires a manual conversion to the working color space.
  30424. *
  30425. * @abstract
  30426. * @param {Texture} texture - The texture to check.
  30427. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30428. */
  30429. needsToWorkingColorSpace( /*texture*/ ) {
  30430. return false;
  30431. }
  30432. /**
  30433. * Returns the component type of a given texture.
  30434. *
  30435. * @param {Texture} texture - The texture.
  30436. * @return {String} The component type.
  30437. */
  30438. getComponentTypeFromTexture( texture ) {
  30439. const type = texture.type;
  30440. if ( texture.isDataTexture ) {
  30441. if ( type === IntType ) return 'int';
  30442. if ( type === UnsignedIntType ) return 'uint';
  30443. }
  30444. return 'float';
  30445. }
  30446. /**
  30447. * Returns the element type for a given type.
  30448. *
  30449. * @param {String} type - The type.
  30450. * @return {String} The element type.
  30451. */
  30452. getElementType( type ) {
  30453. if ( type === 'mat2' ) return 'vec2';
  30454. if ( type === 'mat3' ) return 'vec3';
  30455. if ( type === 'mat4' ) return 'vec4';
  30456. return this.getComponentType( type );
  30457. }
  30458. /**
  30459. * Returns the component type for a given type.
  30460. *
  30461. * @param {String} type - The type.
  30462. * @return {String} The component type.
  30463. */
  30464. getComponentType( type ) {
  30465. type = this.getVectorType( type );
  30466. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30467. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30468. if ( componentType === null ) return null;
  30469. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30470. if ( componentType[ 1 ] === 'i' ) return 'int';
  30471. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30472. return 'float';
  30473. }
  30474. /**
  30475. * Returns the vector type for a given type.
  30476. *
  30477. * @param {String} type - The type.
  30478. * @return {String} The vector type.
  30479. */
  30480. getVectorType( type ) {
  30481. if ( type === 'color' ) return 'vec3';
  30482. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30483. return type;
  30484. }
  30485. /**
  30486. * Returns the data type for the given the length and component type.
  30487. *
  30488. * @param {Number} length - The length.
  30489. * @param {String} [componentType='float'] - The component type.
  30490. * @return {String} The type.
  30491. */
  30492. getTypeFromLength( length, componentType = 'float' ) {
  30493. if ( length === 1 ) return componentType;
  30494. const baseType = getTypeFromLength( length );
  30495. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30496. return prefix + baseType;
  30497. }
  30498. /**
  30499. * Returns the type for a given typed array.
  30500. *
  30501. * @param {TypedArray} array - The typed array.
  30502. * @return {String} The type.
  30503. */
  30504. getTypeFromArray( array ) {
  30505. return typeFromArray.get( array.constructor );
  30506. }
  30507. /**
  30508. * Returns the type for a given buffer attribute.
  30509. *
  30510. * @param {BufferAttribute} attribute - The buffer attribute.
  30511. * @return {String} The type.
  30512. */
  30513. getTypeFromAttribute( attribute ) {
  30514. let dataAttribute = attribute;
  30515. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30516. const array = dataAttribute.array;
  30517. const itemSize = attribute.itemSize;
  30518. const normalized = attribute.normalized;
  30519. let arrayType;
  30520. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30521. arrayType = this.getTypeFromArray( array );
  30522. }
  30523. return this.getTypeFromLength( itemSize, arrayType );
  30524. }
  30525. /**
  30526. * Returns the length for the given data type.
  30527. *
  30528. * @param {String} type - The data type.
  30529. * @return {Number} The length.
  30530. */
  30531. getTypeLength( type ) {
  30532. const vecType = this.getVectorType( type );
  30533. const vecNum = /vec([2-4])/.exec( vecType );
  30534. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30535. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30536. if ( /mat2/.test( type ) === true ) return 4;
  30537. if ( /mat3/.test( type ) === true ) return 9;
  30538. if ( /mat4/.test( type ) === true ) return 16;
  30539. return 0;
  30540. }
  30541. /**
  30542. * Returns the vector type for a given matrix type.
  30543. *
  30544. * @param {String} type - The matrix type.
  30545. * @return {String} The vector type.
  30546. */
  30547. getVectorFromMatrix( type ) {
  30548. return type.replace( 'mat', 'vec' );
  30549. }
  30550. /**
  30551. * For a given type this method changes the component type to the
  30552. * given value. E.g. `vec4` should be changed to the new component type
  30553. * `uint` which results in `uvec4`.
  30554. *
  30555. * @param {String} type - The type.
  30556. * @param {String} newComponentType - The new component type.
  30557. * @return {String} The new type.
  30558. */
  30559. changeComponentType( type, newComponentType ) {
  30560. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30561. }
  30562. /**
  30563. * Returns the integer type pendant for the given type.
  30564. *
  30565. * @param {String} type - The type.
  30566. * @return {String} The integer type.
  30567. */
  30568. getIntegerType( type ) {
  30569. const componentType = this.getComponentType( type );
  30570. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30571. return this.changeComponentType( type, 'int' );
  30572. }
  30573. /**
  30574. * Adds a stack node to the internal stack.
  30575. *
  30576. * @return {StackNode} The added stack node.
  30577. */
  30578. addStack() {
  30579. this.stack = stack( this.stack );
  30580. this.stacks.push( getCurrentStack() || this.stack );
  30581. setCurrentStack( this.stack );
  30582. return this.stack;
  30583. }
  30584. /**
  30585. * Removes the last stack node from the internal stack.
  30586. *
  30587. * @return {StackNode} The removed stack node.
  30588. */
  30589. removeStack() {
  30590. const lastStack = this.stack;
  30591. this.stack = lastStack.parent;
  30592. setCurrentStack( this.stacks.pop() );
  30593. return lastStack;
  30594. }
  30595. /**
  30596. * The builder maintains (cached) data for each node during the building process. This method
  30597. * can be used to get these data for a specific shader stage and cache.
  30598. *
  30599. * @param {Node} node - The node to get the data for.
  30600. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30601. * @param {NodeCache?} cache - An optional cache.
  30602. * @return {Object} The node data.
  30603. */
  30604. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30605. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30606. let nodeData = cache.getData( node );
  30607. if ( nodeData === undefined ) {
  30608. nodeData = {};
  30609. cache.setData( node, nodeData );
  30610. }
  30611. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30612. return nodeData[ shaderStage ];
  30613. }
  30614. /**
  30615. * Returns the properties for the given node and shader stage.
  30616. *
  30617. * @param {Node} node - The node to get the properties for.
  30618. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30619. * @return {Object} The node properties.
  30620. */
  30621. getNodeProperties( node, shaderStage = 'any' ) {
  30622. const nodeData = this.getDataFromNode( node, shaderStage );
  30623. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30624. }
  30625. /**
  30626. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30627. *
  30628. * @param {BufferAttributeNode} node - The buffer attribute node.
  30629. * @param {String} type - The node type.
  30630. * @return {NodeAttribute} The node attribute.
  30631. */
  30632. getBufferAttributeFromNode( node, type ) {
  30633. const nodeData = this.getDataFromNode( node );
  30634. let bufferAttribute = nodeData.bufferAttribute;
  30635. if ( bufferAttribute === undefined ) {
  30636. const index = this.uniforms.index ++;
  30637. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30638. this.bufferAttributes.push( bufferAttribute );
  30639. nodeData.bufferAttribute = bufferAttribute;
  30640. }
  30641. return bufferAttribute;
  30642. }
  30643. /**
  30644. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30645. *
  30646. * @param {OutputStructNode} node - The output struct node.
  30647. * @param {Array<String>} types - The output struct types.
  30648. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30649. * @return {StructTypeNode} The struct type attribute.
  30650. */
  30651. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30652. const nodeData = this.getDataFromNode( node, shaderStage );
  30653. let structType = nodeData.structType;
  30654. if ( structType === undefined ) {
  30655. const index = this.structs.index ++;
  30656. structType = new StructTypeNode( 'StructType' + index, types );
  30657. this.structs[ shaderStage ].push( structType );
  30658. nodeData.structType = structType;
  30659. }
  30660. return structType;
  30661. }
  30662. /**
  30663. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30664. *
  30665. * @param {UniformNode} node - The uniform node.
  30666. * @param {String} type - The uniform type.
  30667. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30668. * @param {String?} name - The name of the uniform.
  30669. * @return {NodeUniform} The node uniform.
  30670. */
  30671. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30672. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30673. let nodeUniform = nodeData.uniform;
  30674. if ( nodeUniform === undefined ) {
  30675. const index = this.uniforms.index ++;
  30676. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30677. this.uniforms[ shaderStage ].push( nodeUniform );
  30678. nodeData.uniform = nodeUniform;
  30679. }
  30680. return nodeUniform;
  30681. }
  30682. /**
  30683. * Returns an instance of {@link NodeVar} for the given variable node.
  30684. *
  30685. * @param {VarNode} node - The variable node.
  30686. * @param {String?} name - The variable's name.
  30687. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30688. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30689. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30690. *
  30691. * @return {NodeVar} The node variable.
  30692. */
  30693. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30694. const nodeData = this.getDataFromNode( node, shaderStage );
  30695. let nodeVar = nodeData.variable;
  30696. if ( nodeVar === undefined ) {
  30697. const idNS = readOnly ? '_const' : '_var';
  30698. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30699. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30700. if ( name === null ) {
  30701. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30702. this.vars[ idNS ] ++;
  30703. }
  30704. nodeVar = new NodeVar( name, type, readOnly );
  30705. if ( ! readOnly ) {
  30706. vars.push( nodeVar );
  30707. }
  30708. nodeData.variable = nodeVar;
  30709. }
  30710. return nodeVar;
  30711. }
  30712. /**
  30713. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30714. *
  30715. * @param {Node} node - The varying node.
  30716. * @return {Boolean} Returns true if deterministic.
  30717. */
  30718. isDeterministic( node ) {
  30719. if ( node.isMathNode ) {
  30720. return this.isDeterministic( node.aNode ) &&
  30721. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30722. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30723. } else if ( node.isOperatorNode ) {
  30724. return this.isDeterministic( node.aNode ) &&
  30725. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30726. } else if ( node.isConstNode ) {
  30727. return true;
  30728. }
  30729. return false;
  30730. }
  30731. /**
  30732. * Returns an instance of {@link NodeVarying} for the given varying node.
  30733. *
  30734. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30735. * @param {String?} name - The varying's name.
  30736. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30737. * @return {NodeVar} The node varying.
  30738. */
  30739. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30740. const nodeData = this.getDataFromNode( node, 'any' );
  30741. let nodeVarying = nodeData.varying;
  30742. if ( nodeVarying === undefined ) {
  30743. const varyings = this.varyings;
  30744. const index = varyings.length;
  30745. if ( name === null ) name = 'nodeVarying' + index;
  30746. nodeVarying = new NodeVarying( name, type );
  30747. varyings.push( nodeVarying );
  30748. nodeData.varying = nodeVarying;
  30749. }
  30750. return nodeVarying;
  30751. }
  30752. /**
  30753. * Returns an instance of {@link NodeCode} for the given code node.
  30754. *
  30755. * @param {CodeNode} node - The code node.
  30756. * @param {String} type - The node type.
  30757. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30758. * @return {NodeCode} The node code.
  30759. */
  30760. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30761. const nodeData = this.getDataFromNode( node );
  30762. let nodeCode = nodeData.code;
  30763. if ( nodeCode === undefined ) {
  30764. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30765. const index = codes.length;
  30766. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30767. codes.push( nodeCode );
  30768. nodeData.code = nodeCode;
  30769. }
  30770. return nodeCode;
  30771. }
  30772. /**
  30773. * Adds a code flow based on the code-block hierarchy.
  30774. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30775. * is only used inside one of these conditionals in the current shader stage.
  30776. *
  30777. * @param {Node} node - The node to add.
  30778. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30779. */
  30780. addFlowCodeHierarchy( node, nodeBlock ) {
  30781. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30782. let needsFlowCode = true;
  30783. let nodeBlockHierarchy = nodeBlock;
  30784. while ( nodeBlockHierarchy ) {
  30785. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30786. needsFlowCode = false;
  30787. break;
  30788. }
  30789. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30790. }
  30791. if ( needsFlowCode ) {
  30792. for ( const flowCode of flowCodes ) {
  30793. this.addLineFlowCode( flowCode );
  30794. }
  30795. }
  30796. }
  30797. /**
  30798. * Add a inline-code to the current flow code-block.
  30799. *
  30800. * @param {Node} node - The node to add.
  30801. * @param {String} code - The code to add.
  30802. * @param {Node} nodeBlock - Current ConditionalNode
  30803. */
  30804. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30805. const nodeData = this.getDataFromNode( node );
  30806. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30807. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30808. flowCodes.push( code );
  30809. codeBlock.set( nodeBlock, true );
  30810. }
  30811. /**
  30812. * Add a inline-code to the current flow.
  30813. *
  30814. * @param {String} code - The code to add.
  30815. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30816. * @return {NodeBuilder} A reference to this node builder.
  30817. */
  30818. addLineFlowCode( code, node = null ) {
  30819. if ( code === '' ) return this;
  30820. if ( node !== null && this.context.nodeBlock ) {
  30821. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30822. }
  30823. code = this.tab + code;
  30824. if ( ! /;\s*$/.test( code ) ) {
  30825. code = code + ';\n';
  30826. }
  30827. this.flow.code += code;
  30828. return this;
  30829. }
  30830. /**
  30831. * Adds a code to the current code flow.
  30832. *
  30833. * @param {String} code - Shader code.
  30834. * @return {NodeBuilder} A reference to this node builder.
  30835. */
  30836. addFlowCode( code ) {
  30837. this.flow.code += code;
  30838. return this;
  30839. }
  30840. /**
  30841. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30842. * Typically used in codes with If,Else.
  30843. *
  30844. * @return {NodeBuilder} A reference to this node builder.
  30845. */
  30846. addFlowTab() {
  30847. this.tab += '\t';
  30848. return this;
  30849. }
  30850. /**
  30851. * Removes a tab.
  30852. *
  30853. * @return {NodeBuilder} A reference to this node builder.
  30854. */
  30855. removeFlowTab() {
  30856. this.tab = this.tab.slice( 0, -1 );
  30857. return this;
  30858. }
  30859. /**
  30860. * Gets the current flow data based on a Node.
  30861. *
  30862. * @param {Node} node - Node that the flow was started.
  30863. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30864. * @return {Object} The flow data.
  30865. */
  30866. getFlowData( node/*, shaderStage*/ ) {
  30867. return this.flowsData.get( node );
  30868. }
  30869. /**
  30870. * Executes the node flow based on a root node to generate the final shader code.
  30871. *
  30872. * @param {Node} node - The node to execute.
  30873. * @return {Object} The code flow.
  30874. */
  30875. flowNode( node ) {
  30876. const output = node.getNodeType( this );
  30877. const flowData = this.flowChildNode( node, output );
  30878. this.flowsData.set( node, flowData );
  30879. return flowData;
  30880. }
  30881. /**
  30882. * Returns the native shader operator name for a given generic name.
  30883. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30884. *
  30885. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30886. * @return {FunctionNode} The build function node.
  30887. */
  30888. buildFunctionNode( shaderNode ) {
  30889. const fn = new FunctionNode();
  30890. const previous = this.currentFunctionNode;
  30891. this.currentFunctionNode = fn;
  30892. fn.code = this.buildFunctionCode( shaderNode );
  30893. this.currentFunctionNode = previous;
  30894. return fn;
  30895. }
  30896. /**
  30897. * Generates a code flow based on a TSL function: Fn().
  30898. *
  30899. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30900. * @return {Object}
  30901. */
  30902. flowShaderNode( shaderNode ) {
  30903. const layout = shaderNode.layout;
  30904. const inputs = {
  30905. [ Symbol.iterator ]() {
  30906. let index = 0;
  30907. const values = Object.values( this );
  30908. return {
  30909. next: () => ( {
  30910. value: values[ index ],
  30911. done: index ++ >= values.length
  30912. } )
  30913. };
  30914. }
  30915. };
  30916. for ( const input of layout.inputs ) {
  30917. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30918. }
  30919. //
  30920. shaderNode.layout = null;
  30921. const callNode = shaderNode.call( inputs );
  30922. const flowData = this.flowStagesNode( callNode, layout.type );
  30923. shaderNode.layout = layout;
  30924. return flowData;
  30925. }
  30926. /**
  30927. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30928. *
  30929. * @param {Node} node - The node to execute.
  30930. * @param {String?} output - Expected output type. For example 'vec3'.
  30931. * @return {Object}
  30932. */
  30933. flowStagesNode( node, output = null ) {
  30934. const previousFlow = this.flow;
  30935. const previousVars = this.vars;
  30936. const previousCache = this.cache;
  30937. const previousBuildStage = this.buildStage;
  30938. const previousStack = this.stack;
  30939. const flow = {
  30940. code: ''
  30941. };
  30942. this.flow = flow;
  30943. this.vars = {};
  30944. this.cache = new NodeCache();
  30945. this.stack = stack();
  30946. for ( const buildStage of defaultBuildStages ) {
  30947. this.setBuildStage( buildStage );
  30948. flow.result = node.build( this, output );
  30949. }
  30950. flow.vars = this.getVars( this.shaderStage );
  30951. this.flow = previousFlow;
  30952. this.vars = previousVars;
  30953. this.cache = previousCache;
  30954. this.stack = previousStack;
  30955. this.setBuildStage( previousBuildStage );
  30956. return flow;
  30957. }
  30958. /**
  30959. * Returns the native shader operator name for a given generic name.
  30960. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30961. *
  30962. * @abstract
  30963. * @param {String} op - The operator name to resolve.
  30964. * @return {String} The resolved operator name.
  30965. */
  30966. getFunctionOperator( /* op */ ) {
  30967. return null;
  30968. }
  30969. /**
  30970. * Generates a code flow based on a child Node.
  30971. *
  30972. * @param {Node} node - The node to execute.
  30973. * @param {String?} output - Expected output type. For example 'vec3'.
  30974. * @return {Object} The code flow.
  30975. */
  30976. flowChildNode( node, output = null ) {
  30977. const previousFlow = this.flow;
  30978. const flow = {
  30979. code: ''
  30980. };
  30981. this.flow = flow;
  30982. flow.result = node.build( this, output );
  30983. this.flow = previousFlow;
  30984. return flow;
  30985. }
  30986. /**
  30987. * Executes a flow of code in a different stage.
  30988. *
  30989. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30990. * return the value in fragment-stage even if it is being executed in an input fragment.
  30991. *
  30992. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30993. * @param {Node} node - The node to execute.
  30994. * @param {String?} output - Expected output type. For example 'vec3'.
  30995. * @param {String?} propertyName - The property name to assign the result.
  30996. * @return {Object}
  30997. */
  30998. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30999. const previousShaderStage = this.shaderStage;
  31000. this.setShaderStage( shaderStage );
  31001. const flowData = this.flowChildNode( node, output );
  31002. if ( propertyName !== null ) {
  31003. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31004. }
  31005. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31006. this.setShaderStage( previousShaderStage );
  31007. return flowData;
  31008. }
  31009. /**
  31010. * Returns an array holding all node attributes of this node builder.
  31011. *
  31012. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31013. */
  31014. getAttributesArray() {
  31015. return this.attributes.concat( this.bufferAttributes );
  31016. }
  31017. /**
  31018. * Returns the attribute definitions as a shader string for the given shader stage.
  31019. *
  31020. * @abstract
  31021. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31022. * @return {String} The attribute code section.
  31023. */
  31024. getAttributes( /*shaderStage*/ ) {
  31025. console.warn( 'Abstract function.' );
  31026. }
  31027. /**
  31028. * Returns the varying definitions as a shader string for the given shader stage.
  31029. *
  31030. * @abstract
  31031. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31032. * @return {String} The varying code section.
  31033. */
  31034. getVaryings( /*shaderStage*/ ) {
  31035. console.warn( 'Abstract function.' );
  31036. }
  31037. /**
  31038. * Returns a single variable definition as a shader string for the given variable type and name.
  31039. *
  31040. * @param {String} type - The variable's type.
  31041. * @param {String} name - The variable's name.
  31042. * @return {String} The shader string.
  31043. */
  31044. getVar( type, name ) {
  31045. return `${ this.getType( type ) } ${ name }`;
  31046. }
  31047. /**
  31048. * Returns the variable definitions as a shader string for the given shader stage.
  31049. *
  31050. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31051. * @return {String} The variable code section.
  31052. */
  31053. getVars( shaderStage ) {
  31054. let snippet = '';
  31055. const vars = this.vars[ shaderStage ];
  31056. if ( vars !== undefined ) {
  31057. for ( const variable of vars ) {
  31058. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31059. }
  31060. }
  31061. return snippet;
  31062. }
  31063. /**
  31064. * Returns the uniform definitions as a shader string for the given shader stage.
  31065. *
  31066. * @abstract
  31067. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31068. * @return {String} The uniform code section.
  31069. */
  31070. getUniforms( /*shaderStage*/ ) {
  31071. console.warn( 'Abstract function.' );
  31072. }
  31073. /**
  31074. * Returns the native code definitions as a shader string for the given shader stage.
  31075. *
  31076. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31077. * @return {String} The native code section.
  31078. */
  31079. getCodes( shaderStage ) {
  31080. const codes = this.codes[ shaderStage ];
  31081. let code = '';
  31082. if ( codes !== undefined ) {
  31083. for ( const nodeCode of codes ) {
  31084. code += nodeCode.code + '\n';
  31085. }
  31086. }
  31087. return code;
  31088. }
  31089. /**
  31090. * Returns the hash of this node builder.
  31091. *
  31092. * @return {String} The hash.
  31093. */
  31094. getHash() {
  31095. return this.vertexShader + this.fragmentShader + this.computeShader;
  31096. }
  31097. /**
  31098. * Sets the current shader stage.
  31099. *
  31100. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31101. */
  31102. setShaderStage( shaderStage ) {
  31103. this.shaderStage = shaderStage;
  31104. }
  31105. /**
  31106. * Returns the current shader stage.
  31107. *
  31108. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31109. */
  31110. getShaderStage() {
  31111. return this.shaderStage;
  31112. }
  31113. /**
  31114. * Sets the current build stage.
  31115. *
  31116. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31117. */
  31118. setBuildStage( buildStage ) {
  31119. this.buildStage = buildStage;
  31120. }
  31121. /**
  31122. * Returns the current build stage.
  31123. *
  31124. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31125. */
  31126. getBuildStage() {
  31127. return this.buildStage;
  31128. }
  31129. /**
  31130. * Controls the code build of the shader stages.
  31131. *
  31132. * @abstract
  31133. */
  31134. buildCode() {
  31135. console.warn( 'Abstract function.' );
  31136. }
  31137. /**
  31138. * Central build method which controls the build for the given object.
  31139. *
  31140. * @return {NodeBuilder} A reference to this node builder.
  31141. */
  31142. build() {
  31143. const { object, material, renderer } = this;
  31144. if ( material !== null ) {
  31145. let nodeMaterial = renderer.library.fromMaterial( material );
  31146. if ( nodeMaterial === null ) {
  31147. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31148. nodeMaterial = new NodeMaterial();
  31149. }
  31150. nodeMaterial.build( this );
  31151. } else {
  31152. this.addFlow( 'compute', object );
  31153. }
  31154. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31155. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31156. // generate() -> stage 3: generate shader
  31157. for ( const buildStage of defaultBuildStages ) {
  31158. this.setBuildStage( buildStage );
  31159. if ( this.context.vertex && this.context.vertex.isNode ) {
  31160. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31161. }
  31162. for ( const shaderStage of shaderStages ) {
  31163. this.setShaderStage( shaderStage );
  31164. const flowNodes = this.flowNodes[ shaderStage ];
  31165. for ( const node of flowNodes ) {
  31166. if ( buildStage === 'generate' ) {
  31167. this.flowNode( node );
  31168. } else {
  31169. node.build( this );
  31170. }
  31171. }
  31172. }
  31173. }
  31174. this.setBuildStage( null );
  31175. this.setShaderStage( null );
  31176. // stage 4: build code for a specific output
  31177. this.buildCode();
  31178. this.buildUpdateNodes();
  31179. return this;
  31180. }
  31181. /**
  31182. * Returns a uniform representation which is later used for UBO generation and rendering.
  31183. *
  31184. * @param {NodeUniform} uniformNode - The uniform node.
  31185. * @param {String} type - The requested type.
  31186. * @return {Uniform} The uniform.
  31187. */
  31188. getNodeUniform( uniformNode, type ) {
  31189. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31190. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31191. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31192. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31193. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31194. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31195. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31196. throw new Error( `Uniform "${type}" not declared.` );
  31197. }
  31198. /**
  31199. * Formats the given shader snippet from a given type into another one. E.g.
  31200. * this method might be used to convert a simple float string `"1.0"` into a
  31201. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31202. *
  31203. * @param {String} snippet - The shader snippet.
  31204. * @param {String} fromType - The source type.
  31205. * @param {String} toType - The target type.
  31206. * @return {String} The updated shader string.
  31207. */
  31208. format( snippet, fromType, toType ) {
  31209. fromType = this.getVectorType( fromType );
  31210. toType = this.getVectorType( toType );
  31211. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31212. return snippet;
  31213. }
  31214. const fromTypeLength = this.getTypeLength( fromType );
  31215. const toTypeLength = this.getTypeLength( toType );
  31216. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31217. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31218. }
  31219. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31220. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31221. }
  31222. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31223. // @TODO: ignore for now
  31224. return snippet;
  31225. }
  31226. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31227. // @TODO: ignore for now
  31228. return snippet;
  31229. }
  31230. if ( fromTypeLength === toTypeLength ) {
  31231. return `${ this.getType( toType ) }( ${ snippet } )`;
  31232. }
  31233. if ( fromTypeLength > toTypeLength ) {
  31234. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31235. }
  31236. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31237. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31238. }
  31239. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31240. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31241. }
  31242. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31243. // convert a number value to vector type, e.g:
  31244. // vec3( 1u ) -> vec3( float( 1u ) )
  31245. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31246. }
  31247. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31248. }
  31249. /**
  31250. * Returns a signature with the engine's current revision.
  31251. *
  31252. * @return {String} The signature.
  31253. */
  31254. getSignature() {
  31255. return `// Three.js r${ REVISION } - Node System\n`;
  31256. }
  31257. // Deprecated
  31258. /**
  31259. * @function
  31260. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31261. *
  31262. * @param {String} [type='NodeMaterial'] - The node material type.
  31263. * @throws {Error}
  31264. */
  31265. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31266. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31267. }
  31268. }
  31269. /**
  31270. * Management class for updating nodes. The module tracks metrics like
  31271. * the elapsed time, delta time, the render and frame ID to correctly
  31272. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31273. * and {@link Node#updateAfter} depending on the node's configuration.
  31274. */
  31275. class NodeFrame {
  31276. /**
  31277. * Constructs a new node fame.
  31278. */
  31279. constructor() {
  31280. /**
  31281. * The elapsed time in seconds.
  31282. *
  31283. * @type {Number}
  31284. * @default 0
  31285. */
  31286. this.time = 0;
  31287. /**
  31288. * The delta time in seconds.
  31289. *
  31290. * @type {Number}
  31291. * @default 0
  31292. */
  31293. this.deltaTime = 0;
  31294. /**
  31295. * The frame ID.
  31296. *
  31297. * @type {Number}
  31298. * @default 0
  31299. */
  31300. this.frameId = 0;
  31301. /**
  31302. * The render ID.
  31303. *
  31304. * @type {Number}
  31305. * @default 0
  31306. */
  31307. this.renderId = 0;
  31308. /**
  31309. * Used to control the {@link Node#update} call.
  31310. *
  31311. * @type {WeakMap<Node, Object>}
  31312. */
  31313. this.updateMap = new WeakMap();
  31314. /**
  31315. * Used to control the {@link Node#updateBefore} call.
  31316. *
  31317. * @type {WeakMap<Node, Object>}
  31318. */
  31319. this.updateBeforeMap = new WeakMap();
  31320. /**
  31321. * Used to control the {@link Node#updateAfter} call.
  31322. *
  31323. * @type {WeakMap<Node, Object>}
  31324. */
  31325. this.updateAfterMap = new WeakMap();
  31326. /**
  31327. * A reference to the current renderer.
  31328. *
  31329. * @type {Renderer?}
  31330. * @default null
  31331. */
  31332. this.renderer = null;
  31333. /**
  31334. * A reference to the current material.
  31335. *
  31336. * @type {Material?}
  31337. * @default null
  31338. */
  31339. this.material = null;
  31340. /**
  31341. * A reference to the current camera.
  31342. *
  31343. * @type {Camera?}
  31344. * @default null
  31345. */
  31346. this.camera = null;
  31347. /**
  31348. * A reference to the current 3D object.
  31349. *
  31350. * @type {Object3D?}
  31351. * @default null
  31352. */
  31353. this.object = null;
  31354. /**
  31355. * A reference to the current scene.
  31356. *
  31357. * @type {Scene?}
  31358. * @default null
  31359. */
  31360. this.scene = null;
  31361. }
  31362. /**
  31363. * Returns a dictionary for a given node and update map which
  31364. * is used to correctly call node update methods per frame or render.
  31365. *
  31366. * @private
  31367. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31368. * @param {Node} nodeRef - The reference to the current node.
  31369. * @return {Object<String,WeakMap>} The dictionary.
  31370. */
  31371. _getMaps( referenceMap, nodeRef ) {
  31372. let maps = referenceMap.get( nodeRef );
  31373. if ( maps === undefined ) {
  31374. maps = {
  31375. renderMap: new WeakMap(),
  31376. frameMap: new WeakMap()
  31377. };
  31378. referenceMap.set( nodeRef, maps );
  31379. }
  31380. return maps;
  31381. }
  31382. /**
  31383. * This method executes the {@link Node#updateBefore} for the given node.
  31384. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31385. * is only executed once per frame, render or object depending on the update
  31386. * type.
  31387. *
  31388. * @param {Node} node - The node that should be updated.
  31389. */
  31390. updateBeforeNode( node ) {
  31391. const updateType = node.getUpdateBeforeType();
  31392. const reference = node.updateReference( this );
  31393. if ( updateType === NodeUpdateType.FRAME ) {
  31394. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31395. if ( frameMap.get( reference ) !== this.frameId ) {
  31396. if ( node.updateBefore( this ) !== false ) {
  31397. frameMap.set( reference, this.frameId );
  31398. }
  31399. }
  31400. } else if ( updateType === NodeUpdateType.RENDER ) {
  31401. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31402. if ( renderMap.get( reference ) !== this.renderId ) {
  31403. if ( node.updateBefore( this ) !== false ) {
  31404. renderMap.set( reference, this.renderId );
  31405. }
  31406. }
  31407. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31408. node.updateBefore( this );
  31409. }
  31410. }
  31411. /**
  31412. * This method executes the {@link Node#updateAfter} for the given node.
  31413. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31414. * is only executed once per frame, render or object depending on the update
  31415. * type.
  31416. *
  31417. * @param {Node} node - The node that should be updated.
  31418. */
  31419. updateAfterNode( node ) {
  31420. const updateType = node.getUpdateAfterType();
  31421. const reference = node.updateReference( this );
  31422. if ( updateType === NodeUpdateType.FRAME ) {
  31423. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31424. if ( frameMap.get( reference ) !== this.frameId ) {
  31425. if ( node.updateAfter( this ) !== false ) {
  31426. frameMap.set( reference, this.frameId );
  31427. }
  31428. }
  31429. } else if ( updateType === NodeUpdateType.RENDER ) {
  31430. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31431. if ( renderMap.get( reference ) !== this.renderId ) {
  31432. if ( node.updateAfter( this ) !== false ) {
  31433. renderMap.set( reference, this.renderId );
  31434. }
  31435. }
  31436. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31437. node.updateAfter( this );
  31438. }
  31439. }
  31440. /**
  31441. * This method executes the {@link Node#update} for the given node.
  31442. * It makes sure {@link Node#updateType} is honored meaning the update
  31443. * is only executed once per frame, render or object depending on the update
  31444. * type.
  31445. *
  31446. * @param {Node} node - The node that should be updated.
  31447. */
  31448. updateNode( node ) {
  31449. const updateType = node.getUpdateType();
  31450. const reference = node.updateReference( this );
  31451. if ( updateType === NodeUpdateType.FRAME ) {
  31452. const { frameMap } = this._getMaps( this.updateMap, reference );
  31453. if ( frameMap.get( reference ) !== this.frameId ) {
  31454. if ( node.update( this ) !== false ) {
  31455. frameMap.set( reference, this.frameId );
  31456. }
  31457. }
  31458. } else if ( updateType === NodeUpdateType.RENDER ) {
  31459. const { renderMap } = this._getMaps( this.updateMap, reference );
  31460. if ( renderMap.get( reference ) !== this.renderId ) {
  31461. if ( node.update( this ) !== false ) {
  31462. renderMap.set( reference, this.renderId );
  31463. }
  31464. }
  31465. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31466. node.update( this );
  31467. }
  31468. }
  31469. /**
  31470. * Updates the internal state of the node frame. This method is
  31471. * called by the renderer in its internal animation loop.
  31472. */
  31473. update() {
  31474. this.frameId ++;
  31475. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31476. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31477. this.lastTime = performance.now();
  31478. this.time += this.deltaTime;
  31479. }
  31480. }
  31481. /**
  31482. * Describes the input of a {@link NodeFunction}.
  31483. */
  31484. class NodeFunctionInput {
  31485. /**
  31486. * Constructs a new node function input.
  31487. *
  31488. * @param {String} type - The input type.
  31489. * @param {String} name - The input name.
  31490. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31491. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31492. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31493. */
  31494. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31495. /**
  31496. * The input type.
  31497. *
  31498. * @type {String}
  31499. */
  31500. this.type = type;
  31501. /**
  31502. * The input name.
  31503. *
  31504. * @type {String}
  31505. */
  31506. this.name = name;
  31507. /**
  31508. * If the input is an Array, count will be the length.
  31509. *
  31510. * @type {Number?}
  31511. * @default null
  31512. */
  31513. this.count = count;
  31514. /**
  31515. *The parameter qualifier (only relevant for GLSL).
  31516. *
  31517. * @type {('in'|'out'|'inout')}
  31518. * @default ''
  31519. */
  31520. this.qualifier = qualifier;
  31521. /**
  31522. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31523. *
  31524. * @type {Boolean}
  31525. * @default false
  31526. */
  31527. this.isConst = isConst;
  31528. }
  31529. }
  31530. NodeFunctionInput.isNodeFunctionInput = true;
  31531. /**
  31532. * Module for representing directional lights as nodes.
  31533. *
  31534. * @augments AnalyticLightNode
  31535. */
  31536. class DirectionalLightNode extends AnalyticLightNode {
  31537. static get type() {
  31538. return 'DirectionalLightNode';
  31539. }
  31540. /**
  31541. * Constructs a new directional light node.
  31542. *
  31543. * @param {DirectionalLight?} [light=null] - The directional light source.
  31544. */
  31545. constructor( light = null ) {
  31546. super( light );
  31547. }
  31548. setup( builder ) {
  31549. super.setup( builder );
  31550. const lightingModel = builder.context.lightingModel;
  31551. const lightColor = this.colorNode;
  31552. const lightDirection = lightTargetDirection( this.light );
  31553. const reflectedLight = builder.context.reflectedLight;
  31554. lightingModel.direct( {
  31555. lightDirection,
  31556. lightColor,
  31557. reflectedLight
  31558. }, builder.stack, builder );
  31559. }
  31560. }
  31561. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31562. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31563. let _ltcLib = null;
  31564. /**
  31565. * Module for representing rect area lights as nodes.
  31566. *
  31567. * @augments AnalyticLightNode
  31568. */
  31569. class RectAreaLightNode extends AnalyticLightNode {
  31570. static get type() {
  31571. return 'RectAreaLightNode';
  31572. }
  31573. /**
  31574. * Constructs a new rect area light node.
  31575. *
  31576. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31577. */
  31578. constructor( light = null ) {
  31579. super( light );
  31580. /**
  31581. * Uniform node representing the half height of the are light.
  31582. *
  31583. * @type {UniformNode<vec3>}
  31584. */
  31585. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31586. /**
  31587. * Uniform node representing the half width of the are light.
  31588. *
  31589. * @type {UniformNode<vec3>}
  31590. */
  31591. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31592. /**
  31593. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31594. * relies on `viewMatrix` which might vary per render call.
  31595. *
  31596. * @type {String}
  31597. * @default 'render'
  31598. */
  31599. this.updateType = NodeUpdateType.RENDER;
  31600. }
  31601. /**
  31602. * Overwritten to updated rect area light specific uniforms.
  31603. *
  31604. * @param {NodeFrame} frame - A reference to the current node frame.
  31605. */
  31606. update( frame ) {
  31607. super.update( frame );
  31608. const { light } = this;
  31609. const viewMatrix = frame.camera.matrixWorldInverse;
  31610. _matrix42.identity();
  31611. _matrix41.copy( light.matrixWorld );
  31612. _matrix41.premultiply( viewMatrix );
  31613. _matrix42.extractRotation( _matrix41 );
  31614. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31615. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31616. this.halfWidth.value.applyMatrix4( _matrix42 );
  31617. this.halfHeight.value.applyMatrix4( _matrix42 );
  31618. }
  31619. setup( builder ) {
  31620. super.setup( builder );
  31621. let ltc_1, ltc_2;
  31622. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31623. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31624. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31625. } else {
  31626. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31627. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31628. }
  31629. const { colorNode, light } = this;
  31630. const lightingModel = builder.context.lightingModel;
  31631. const lightPosition = lightViewPosition( light );
  31632. const reflectedLight = builder.context.reflectedLight;
  31633. lightingModel.directRectArea( {
  31634. lightColor: colorNode,
  31635. lightPosition,
  31636. halfWidth: this.halfWidth,
  31637. halfHeight: this.halfHeight,
  31638. reflectedLight,
  31639. ltc_1,
  31640. ltc_2
  31641. }, builder.stack, builder );
  31642. }
  31643. /**
  31644. * Used to configure the internal BRDF approximation texture data.
  31645. *
  31646. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31647. */
  31648. static setLTC( ltc ) {
  31649. _ltcLib = ltc;
  31650. }
  31651. }
  31652. /**
  31653. * Module for representing spot lights as nodes.
  31654. *
  31655. * @augments AnalyticLightNode
  31656. */
  31657. class SpotLightNode extends AnalyticLightNode {
  31658. static get type() {
  31659. return 'SpotLightNode';
  31660. }
  31661. /**
  31662. * Constructs a new spot light node.
  31663. *
  31664. * @param {SpotLight?} [light=null] - The spot light source.
  31665. */
  31666. constructor( light = null ) {
  31667. super( light );
  31668. /**
  31669. * Uniform node representing the cone cosine.
  31670. *
  31671. * @type {UniformNode<float>}
  31672. */
  31673. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31674. /**
  31675. * Uniform node representing the penumbra cosine.
  31676. *
  31677. * @type {UniformNode<float>}
  31678. */
  31679. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31680. /**
  31681. * Uniform node representing the cutoff distance.
  31682. *
  31683. * @type {UniformNode<float>}
  31684. */
  31685. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31686. /**
  31687. * Uniform node representing the decay exponent.
  31688. *
  31689. * @type {UniformNode<float>}
  31690. */
  31691. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31692. }
  31693. /**
  31694. * Overwritten to updated spot light specific uniforms.
  31695. *
  31696. * @param {NodeFrame} frame - A reference to the current node frame.
  31697. */
  31698. update( frame ) {
  31699. super.update( frame );
  31700. const { light } = this;
  31701. this.coneCosNode.value = Math.cos( light.angle );
  31702. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31703. this.cutoffDistanceNode.value = light.distance;
  31704. this.decayExponentNode.value = light.decay;
  31705. }
  31706. /**
  31707. * Computes the spot attenuation for the given angle.
  31708. *
  31709. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31710. * @return {Node<float>} The spot attenuation.
  31711. */
  31712. getSpotAttenuation( angleCosine ) {
  31713. const { coneCosNode, penumbraCosNode } = this;
  31714. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31715. }
  31716. setup( builder ) {
  31717. super.setup( builder );
  31718. const lightingModel = builder.context.lightingModel;
  31719. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31720. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31721. const lightDirection = lVector.normalize();
  31722. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31723. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31724. const lightDistance = lVector.length();
  31725. const lightAttenuation = getDistanceAttenuation( {
  31726. lightDistance,
  31727. cutoffDistance: cutoffDistanceNode,
  31728. decayExponent: decayExponentNode
  31729. } );
  31730. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31731. if ( light.map ) {
  31732. const spotLightCoord = lightProjectionUV( light );
  31733. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31734. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31735. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31736. }
  31737. const reflectedLight = builder.context.reflectedLight;
  31738. lightingModel.direct( {
  31739. lightDirection,
  31740. lightColor,
  31741. reflectedLight
  31742. }, builder.stack, builder );
  31743. }
  31744. }
  31745. /**
  31746. * An IES version of the default spot light node.
  31747. *
  31748. * @augments SpotLightNode
  31749. */
  31750. class IESSpotLightNode extends SpotLightNode {
  31751. static get type() {
  31752. return 'IESSpotLightNode';
  31753. }
  31754. /**
  31755. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31756. *
  31757. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31758. * @return {Node<float>} The spot attenuation.
  31759. */
  31760. getSpotAttenuation( angleCosine ) {
  31761. const iesMap = this.light.iesMap;
  31762. let spotAttenuation = null;
  31763. if ( iesMap && iesMap.isTexture === true ) {
  31764. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31765. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31766. } else {
  31767. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31768. }
  31769. return spotAttenuation;
  31770. }
  31771. }
  31772. /**
  31773. * Module for representing ambient lights as nodes.
  31774. *
  31775. * @augments AnalyticLightNode
  31776. */
  31777. class AmbientLightNode extends AnalyticLightNode {
  31778. static get type() {
  31779. return 'AmbientLightNode';
  31780. }
  31781. /**
  31782. * Constructs a new ambient light node.
  31783. *
  31784. * @param {AmbientLight?} [light=null] - The ambient light source.
  31785. */
  31786. constructor( light = null ) {
  31787. super( light );
  31788. }
  31789. setup( { context } ) {
  31790. context.irradiance.addAssign( this.colorNode );
  31791. }
  31792. }
  31793. /**
  31794. * Module for representing hemisphere lights as nodes.
  31795. *
  31796. * @augments AnalyticLightNode
  31797. */
  31798. class HemisphereLightNode extends AnalyticLightNode {
  31799. static get type() {
  31800. return 'HemisphereLightNode';
  31801. }
  31802. /**
  31803. * Constructs a new hemisphere light node.
  31804. *
  31805. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31806. */
  31807. constructor( light = null ) {
  31808. super( light );
  31809. /**
  31810. * Uniform node representing the light's position.
  31811. *
  31812. * @type {UniformNode<vec3>}
  31813. */
  31814. this.lightPositionNode = lightPosition( light );
  31815. /**
  31816. * A node representing the light's direction.
  31817. *
  31818. * @type {Node<vec3>}
  31819. */
  31820. this.lightDirectionNode = this.lightPositionNode.normalize();
  31821. /**
  31822. * Uniform node representing the light's ground color.
  31823. *
  31824. * @type {UniformNode<vec3>}
  31825. */
  31826. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31827. }
  31828. /**
  31829. * Overwritten to updated hemisphere light specific uniforms.
  31830. *
  31831. * @param {NodeFrame} frame - A reference to the current node frame.
  31832. */
  31833. update( frame ) {
  31834. const { light } = this;
  31835. super.update( frame );
  31836. this.lightPositionNode.object3d = light;
  31837. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31838. }
  31839. setup( builder ) {
  31840. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31841. const dotNL = normalView.dot( lightDirectionNode );
  31842. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31843. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31844. builder.context.irradiance.addAssign( irradiance );
  31845. }
  31846. }
  31847. /**
  31848. * Module for representing light probes as nodes.
  31849. *
  31850. * @augments AnalyticLightNode
  31851. */
  31852. class LightProbeNode extends AnalyticLightNode {
  31853. static get type() {
  31854. return 'LightProbeNode';
  31855. }
  31856. /**
  31857. * Constructs a new light probe node.
  31858. *
  31859. * @param {LightProbe?} [light=null] - The light probe.
  31860. */
  31861. constructor( light = null ) {
  31862. super( light );
  31863. const array = [];
  31864. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31865. /**
  31866. * Light probe represented as a uniform of spherical harmonics.
  31867. *
  31868. * @type {UniformArrayNode}
  31869. */
  31870. this.lightProbe = uniformArray( array );
  31871. }
  31872. /**
  31873. * Overwritten to updated light probe specific uniforms.
  31874. *
  31875. * @param {NodeFrame} frame - A reference to the current node frame.
  31876. */
  31877. update( frame ) {
  31878. const { light } = this;
  31879. super.update( frame );
  31880. //
  31881. for ( let i = 0; i < 9; i ++ ) {
  31882. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31883. }
  31884. }
  31885. setup( builder ) {
  31886. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31887. builder.context.irradiance.addAssign( irradiance );
  31888. }
  31889. }
  31890. /**
  31891. * Base class for node parsers. A derived parser must be implemented
  31892. * for each supported native shader language.
  31893. */
  31894. class NodeParser {
  31895. /**
  31896. * The method parses the given native code an returns a node function.
  31897. *
  31898. * @abstract
  31899. * @param {String} source - The native shader code.
  31900. * @return {NodeFunction} A node function.
  31901. */
  31902. parseFunction( /*source*/ ) {
  31903. console.warn( 'Abstract function.' );
  31904. }
  31905. }
  31906. /**
  31907. * Base class for node functions. A derived module must be implemented
  31908. * for each supported native shader language. Similar to other `Node*` modules,
  31909. * this class is only relevant during the building process and not used
  31910. * in user-level code.
  31911. */
  31912. class NodeFunction {
  31913. /**
  31914. * Constructs a new node function.
  31915. *
  31916. * @param {String} type - The node type. This type is the return type of the node function.
  31917. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31918. * @param {String} [name=''] - The function's name.
  31919. * @param {String} [precision=''] - The precision qualifier.
  31920. */
  31921. constructor( type, inputs, name = '', precision = '' ) {
  31922. /**
  31923. * The node type. This type is the return type of the node function.
  31924. *
  31925. * @type {String}
  31926. */
  31927. this.type = type;
  31928. /**
  31929. * The function's inputs.
  31930. *
  31931. * @type {Array<NodeFunctionInput>}
  31932. */
  31933. this.inputs = inputs;
  31934. /**
  31935. * The name of the uniform.
  31936. *
  31937. * @type {String}
  31938. * @default ''
  31939. */
  31940. this.name = name;
  31941. /**
  31942. * The precision qualifier.
  31943. *
  31944. * @type {String}
  31945. * @default ''
  31946. */
  31947. this.precision = precision;
  31948. }
  31949. /**
  31950. * This method returns the native code of the node function.
  31951. *
  31952. * @abstract
  31953. * @param {String} name - The function's name.
  31954. * @return {String} A shader code.
  31955. */
  31956. getCode( /*name = this.name*/ ) {
  31957. console.warn( 'Abstract function.' );
  31958. }
  31959. }
  31960. NodeFunction.isNodeFunction = true;
  31961. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31962. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31963. const pragmaMain = '#pragma main';
  31964. const parse$1 = ( source ) => {
  31965. source = source.trim();
  31966. const pragmaMainIndex = source.indexOf( pragmaMain );
  31967. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31968. const declaration = mainCode.match( declarationRegexp$1 );
  31969. if ( declaration !== null && declaration.length === 5 ) {
  31970. // tokenizer
  31971. const inputsCode = declaration[ 4 ];
  31972. const propsMatches = [];
  31973. let nameMatch = null;
  31974. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31975. propsMatches.push( nameMatch );
  31976. }
  31977. // parser
  31978. const inputs = [];
  31979. let i = 0;
  31980. while ( i < propsMatches.length ) {
  31981. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31982. if ( isConst === true ) {
  31983. i ++;
  31984. }
  31985. let qualifier = propsMatches[ i ][ 0 ];
  31986. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31987. i ++;
  31988. } else {
  31989. qualifier = '';
  31990. }
  31991. const type = propsMatches[ i ++ ][ 0 ];
  31992. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31993. if ( Number.isNaN( count ) === false ) i ++;
  31994. else count = null;
  31995. const name = propsMatches[ i ++ ][ 0 ];
  31996. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31997. }
  31998. //
  31999. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32000. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32001. const type = declaration[ 2 ];
  32002. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32003. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  32004. return {
  32005. type,
  32006. inputs,
  32007. name,
  32008. precision,
  32009. inputsCode,
  32010. blockCode,
  32011. headerCode
  32012. };
  32013. } else {
  32014. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32015. }
  32016. };
  32017. /**
  32018. * This class represents a GLSL node function.
  32019. *
  32020. * @augments NodeFunction
  32021. */
  32022. class GLSLNodeFunction extends NodeFunction {
  32023. /**
  32024. * Constructs a new GLSL node function.
  32025. *
  32026. * @param {String} source - The GLSL source.
  32027. */
  32028. constructor( source ) {
  32029. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32030. super( type, inputs, name, precision );
  32031. this.inputsCode = inputsCode;
  32032. this.blockCode = blockCode;
  32033. this.headerCode = headerCode;
  32034. }
  32035. /**
  32036. * This method returns the GLSL code of the node function.
  32037. *
  32038. * @param {String} [name=this.name] - The function's name.
  32039. * @return {String} The shader code.
  32040. */
  32041. getCode( name = this.name ) {
  32042. let code;
  32043. const blockCode = this.blockCode;
  32044. if ( blockCode !== '' ) {
  32045. const { type, inputsCode, headerCode, precision } = this;
  32046. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32047. if ( precision !== '' ) {
  32048. declarationCode = `${ precision } ${ declarationCode }`;
  32049. }
  32050. code = headerCode + declarationCode + blockCode;
  32051. } else {
  32052. // interface function
  32053. code = '';
  32054. }
  32055. return code;
  32056. }
  32057. }
  32058. /**
  32059. * A GLSL node parser.
  32060. *
  32061. * @augments NodeParser
  32062. */
  32063. class GLSLNodeParser extends NodeParser {
  32064. /**
  32065. * The method parses the given GLSL code an returns a node function.
  32066. *
  32067. * @param {String} source - The GLSL code.
  32068. * @return {GLSLNodeFunction} A node function.
  32069. */
  32070. parseFunction( source ) {
  32071. return new GLSLNodeFunction( source );
  32072. }
  32073. }
  32074. const _outputNodeMap = new WeakMap();
  32075. const _chainKeys$2 = [];
  32076. const _cacheKeyValues = [];
  32077. /**
  32078. * This renderer module manages node-related objects and is the
  32079. * primary interface between the renderer and the node system.
  32080. *
  32081. * @private
  32082. * @augments DataMap
  32083. */
  32084. class Nodes extends DataMap {
  32085. /**
  32086. * Constructs a new nodes management component.
  32087. *
  32088. * @param {Renderer} renderer - The renderer.
  32089. * @param {Backend} backend - The renderer's backend.
  32090. */
  32091. constructor( renderer, backend ) {
  32092. super();
  32093. /**
  32094. * The renderer.
  32095. *
  32096. * @type {Renderer}
  32097. */
  32098. this.renderer = renderer;
  32099. /**
  32100. * The renderer's backend.
  32101. *
  32102. * @type {Backend}
  32103. */
  32104. this.backend = backend;
  32105. /**
  32106. * The node frame.
  32107. *
  32108. * @type {Renderer}
  32109. */
  32110. this.nodeFrame = new NodeFrame();
  32111. /**
  32112. * A cache for managing node builder states.
  32113. *
  32114. * @type {Map<Number,NodeBuilderState>}
  32115. */
  32116. this.nodeBuilderCache = new Map();
  32117. /**
  32118. * A cache for managing data cache key data.
  32119. *
  32120. * @type {ChainMap}
  32121. */
  32122. this.callHashCache = new ChainMap();
  32123. /**
  32124. * A cache for managing node uniforms group data.
  32125. *
  32126. * @type {ChainMap}
  32127. */
  32128. this.groupsData = new ChainMap();
  32129. /**
  32130. * A cache for managing node objects of
  32131. * scene properties like fog or environments.
  32132. *
  32133. * @type {Object<String,WeakMap>}
  32134. */
  32135. this.cacheLib = {};
  32136. }
  32137. /**
  32138. * Returns `true` if the given node uniforms group must be updated or not.
  32139. *
  32140. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32141. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32142. */
  32143. updateGroup( nodeUniformsGroup ) {
  32144. const groupNode = nodeUniformsGroup.groupNode;
  32145. const name = groupNode.name;
  32146. // objectGroup is always updated
  32147. if ( name === objectGroup.name ) return true;
  32148. // renderGroup is updated once per render/compute call
  32149. if ( name === renderGroup.name ) {
  32150. const uniformsGroupData = this.get( nodeUniformsGroup );
  32151. const renderId = this.nodeFrame.renderId;
  32152. if ( uniformsGroupData.renderId !== renderId ) {
  32153. uniformsGroupData.renderId = renderId;
  32154. return true;
  32155. }
  32156. return false;
  32157. }
  32158. // frameGroup is updated once per frame
  32159. if ( name === frameGroup.name ) {
  32160. const uniformsGroupData = this.get( nodeUniformsGroup );
  32161. const frameId = this.nodeFrame.frameId;
  32162. if ( uniformsGroupData.frameId !== frameId ) {
  32163. uniformsGroupData.frameId = frameId;
  32164. return true;
  32165. }
  32166. return false;
  32167. }
  32168. // other groups are updated just when groupNode.needsUpdate is true
  32169. _chainKeys$2[ 0 ] = groupNode;
  32170. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32171. let groupData = this.groupsData.get( _chainKeys$2 );
  32172. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32173. _chainKeys$2.length = 0;
  32174. if ( groupData.version !== groupNode.version ) {
  32175. groupData.version = groupNode.version;
  32176. return true;
  32177. }
  32178. return false;
  32179. }
  32180. /**
  32181. * Returns the cache key for the given render object.
  32182. *
  32183. * @param {RenderObject} renderObject - The render object.
  32184. * @return {Number} The cache key.
  32185. */
  32186. getForRenderCacheKey( renderObject ) {
  32187. return renderObject.initialCacheKey;
  32188. }
  32189. /**
  32190. * Returns a node builder state for the given render object.
  32191. *
  32192. * @param {RenderObject} renderObject - The render object.
  32193. * @return {NodeBuilderState} The node builder state.
  32194. */
  32195. getForRender( renderObject ) {
  32196. const renderObjectData = this.get( renderObject );
  32197. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32198. if ( nodeBuilderState === undefined ) {
  32199. const { nodeBuilderCache } = this;
  32200. const cacheKey = this.getForRenderCacheKey( renderObject );
  32201. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32202. if ( nodeBuilderState === undefined ) {
  32203. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32204. nodeBuilder.scene = renderObject.scene;
  32205. nodeBuilder.material = renderObject.material;
  32206. nodeBuilder.camera = renderObject.camera;
  32207. nodeBuilder.context.material = renderObject.material;
  32208. nodeBuilder.lightsNode = renderObject.lightsNode;
  32209. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32210. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32211. nodeBuilder.clippingContext = renderObject.clippingContext;
  32212. nodeBuilder.build();
  32213. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32214. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32215. }
  32216. nodeBuilderState.usedTimes ++;
  32217. renderObjectData.nodeBuilderState = nodeBuilderState;
  32218. }
  32219. return nodeBuilderState;
  32220. }
  32221. /**
  32222. * Deletes the given object from the internal data map
  32223. *
  32224. * @param {Any} object - The object to delete.
  32225. * @return {Object?} The deleted dictionary.
  32226. */
  32227. delete( object ) {
  32228. if ( object.isRenderObject ) {
  32229. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32230. nodeBuilderState.usedTimes --;
  32231. if ( nodeBuilderState.usedTimes === 0 ) {
  32232. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32233. }
  32234. }
  32235. return super.delete( object );
  32236. }
  32237. /**
  32238. * Returns a node builder state for the given compute node.
  32239. *
  32240. * @param {Node} computeNode - The compute node.
  32241. * @return {NodeBuilderState} The node builder state.
  32242. */
  32243. getForCompute( computeNode ) {
  32244. const computeData = this.get( computeNode );
  32245. let nodeBuilderState = computeData.nodeBuilderState;
  32246. if ( nodeBuilderState === undefined ) {
  32247. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32248. nodeBuilder.build();
  32249. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32250. computeData.nodeBuilderState = nodeBuilderState;
  32251. }
  32252. return nodeBuilderState;
  32253. }
  32254. /**
  32255. * Creates a node builder state for the given node builder.
  32256. *
  32257. * @private
  32258. * @param {NodeBuilder} nodeBuilder - The node builder.
  32259. * @return {NodeBuilderState} The node builder state.
  32260. */
  32261. _createNodeBuilderState( nodeBuilder ) {
  32262. return new NodeBuilderState(
  32263. nodeBuilder.vertexShader,
  32264. nodeBuilder.fragmentShader,
  32265. nodeBuilder.computeShader,
  32266. nodeBuilder.getAttributesArray(),
  32267. nodeBuilder.getBindings(),
  32268. nodeBuilder.updateNodes,
  32269. nodeBuilder.updateBeforeNodes,
  32270. nodeBuilder.updateAfterNodes,
  32271. nodeBuilder.observer,
  32272. nodeBuilder.transforms
  32273. );
  32274. }
  32275. /**
  32276. * Returns an environment node for the current configured
  32277. * scene environment.
  32278. *
  32279. * @param {Scene} scene - The scene.
  32280. * @return {Node} A node representing the current scene environment.
  32281. */
  32282. getEnvironmentNode( scene ) {
  32283. this.updateEnvironment( scene );
  32284. let environmentNode = null;
  32285. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32286. environmentNode = scene.environmentNode;
  32287. } else {
  32288. const sceneData = this.get( scene );
  32289. if ( sceneData.environmentNode ) {
  32290. environmentNode = sceneData.environmentNode;
  32291. }
  32292. }
  32293. return environmentNode;
  32294. }
  32295. /**
  32296. * Returns a background node for the current configured
  32297. * scene background.
  32298. *
  32299. * @param {Scene} scene - The scene.
  32300. * @return {Node} A node representing the current scene background.
  32301. */
  32302. getBackgroundNode( scene ) {
  32303. this.updateBackground( scene );
  32304. let backgroundNode = null;
  32305. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32306. backgroundNode = scene.backgroundNode;
  32307. } else {
  32308. const sceneData = this.get( scene );
  32309. if ( sceneData.backgroundNode ) {
  32310. backgroundNode = sceneData.backgroundNode;
  32311. }
  32312. }
  32313. return backgroundNode;
  32314. }
  32315. /**
  32316. * Returns a fog node for the current configured scene fog.
  32317. *
  32318. * @param {Scene} scene - The scene.
  32319. * @return {Node} A node representing the current scene fog.
  32320. */
  32321. getFogNode( scene ) {
  32322. this.updateFog( scene );
  32323. return scene.fogNode || this.get( scene ).fogNode || null;
  32324. }
  32325. /**
  32326. * Returns a cache key for the given scene and lights node.
  32327. * This key is used by `RenderObject` as a part of the dynamic
  32328. * cache key (a key that must be checked every time the render
  32329. * objects is drawn).
  32330. *
  32331. * @param {Scene} scene - The scene.
  32332. * @param {LightsNode} lightsNode - The lights node.
  32333. * @return {Number} The cache key.
  32334. */
  32335. getCacheKey( scene, lightsNode ) {
  32336. _chainKeys$2[ 0 ] = scene;
  32337. _chainKeys$2[ 1 ] = lightsNode;
  32338. const callId = this.renderer.info.calls;
  32339. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32340. if ( cacheKeyData.callId !== callId ) {
  32341. const environmentNode = this.getEnvironmentNode( scene );
  32342. const fogNode = this.getFogNode( scene );
  32343. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32344. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32345. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32346. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32347. cacheKeyData.callId = callId;
  32348. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32349. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32350. _cacheKeyValues.length = 0;
  32351. }
  32352. _chainKeys$2.length = 0;
  32353. return cacheKeyData.cacheKey;
  32354. }
  32355. /**
  32356. * A boolean that indicates whether tone mapping should be enabled
  32357. * or not.
  32358. *
  32359. * @type {Boolean}
  32360. */
  32361. get isToneMappingState() {
  32362. return this.renderer.getRenderTarget() ? false : true;
  32363. }
  32364. /**
  32365. * If a scene background is configured, this method makes sure to
  32366. * represent the background with a corresponding node-based implementation.
  32367. *
  32368. * @param {Scene} scene - The scene.
  32369. */
  32370. updateBackground( scene ) {
  32371. const sceneData = this.get( scene );
  32372. const background = scene.background;
  32373. if ( background ) {
  32374. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32375. if ( sceneData.background !== background || forceUpdate ) {
  32376. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32377. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32378. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32379. return pmremTexture( background );
  32380. } else {
  32381. let envMap;
  32382. if ( background.isCubeTexture === true ) {
  32383. envMap = cubeTexture( background );
  32384. } else {
  32385. envMap = texture( background );
  32386. }
  32387. return cubeMapNode( envMap );
  32388. }
  32389. } else if ( background.isTexture === true ) {
  32390. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32391. } else if ( background.isColor !== true ) {
  32392. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32393. }
  32394. }, forceUpdate );
  32395. sceneData.backgroundNode = backgroundNode;
  32396. sceneData.background = background;
  32397. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32398. }
  32399. } else if ( sceneData.backgroundNode ) {
  32400. delete sceneData.backgroundNode;
  32401. delete sceneData.background;
  32402. }
  32403. }
  32404. /**
  32405. * This method is part of the caching of nodes which are used to represents the
  32406. * scene's background, fog or environment.
  32407. *
  32408. * @param {String} type - The type of object to cache.
  32409. * @param {Object} object - The object.
  32410. * @param {Function} callback - A callback that produces a node representation for the given object.
  32411. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32412. * @return {Node} The node representation.
  32413. */
  32414. getCacheNode( type, object, callback, forceUpdate = false ) {
  32415. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32416. let node = nodeCache.get( object );
  32417. if ( node === undefined || forceUpdate ) {
  32418. node = callback();
  32419. nodeCache.set( object, node );
  32420. }
  32421. return node;
  32422. }
  32423. /**
  32424. * If a scene fog is configured, this method makes sure to
  32425. * represent the fog with a corresponding node-based implementation.
  32426. *
  32427. * @param {Scene} scene - The scene.
  32428. */
  32429. updateFog( scene ) {
  32430. const sceneData = this.get( scene );
  32431. const sceneFog = scene.fog;
  32432. if ( sceneFog ) {
  32433. if ( sceneData.fog !== sceneFog ) {
  32434. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32435. if ( sceneFog.isFogExp2 ) {
  32436. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32437. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32438. return fog( color, densityFogFactor( density ) );
  32439. } else if ( sceneFog.isFog ) {
  32440. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32441. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32442. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32443. return fog( color, rangeFogFactor( near, far ) );
  32444. } else {
  32445. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32446. }
  32447. } );
  32448. sceneData.fogNode = fogNode;
  32449. sceneData.fog = sceneFog;
  32450. }
  32451. } else {
  32452. delete sceneData.fogNode;
  32453. delete sceneData.fog;
  32454. }
  32455. }
  32456. /**
  32457. * If a scene environment is configured, this method makes sure to
  32458. * represent the environment with a corresponding node-based implementation.
  32459. *
  32460. * @param {Scene} scene - The scene.
  32461. */
  32462. updateEnvironment( scene ) {
  32463. const sceneData = this.get( scene );
  32464. const environment = scene.environment;
  32465. if ( environment ) {
  32466. if ( sceneData.environment !== environment ) {
  32467. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32468. if ( environment.isCubeTexture === true ) {
  32469. return cubeTexture( environment );
  32470. } else if ( environment.isTexture === true ) {
  32471. return texture( environment );
  32472. } else {
  32473. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32474. }
  32475. } );
  32476. sceneData.environmentNode = environmentNode;
  32477. sceneData.environment = environment;
  32478. }
  32479. } else if ( sceneData.environmentNode ) {
  32480. delete sceneData.environmentNode;
  32481. delete sceneData.environment;
  32482. }
  32483. }
  32484. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32485. const nodeFrame = this.nodeFrame;
  32486. nodeFrame.renderer = renderer;
  32487. nodeFrame.scene = scene;
  32488. nodeFrame.object = object;
  32489. nodeFrame.camera = camera;
  32490. nodeFrame.material = material;
  32491. return nodeFrame;
  32492. }
  32493. getNodeFrameForRender( renderObject ) {
  32494. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32495. }
  32496. /**
  32497. * Returns the current output cache key.
  32498. *
  32499. * @return {String} The output cache key.
  32500. */
  32501. getOutputCacheKey() {
  32502. const renderer = this.renderer;
  32503. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32504. }
  32505. /**
  32506. * Checks if the output configuration (tone mapping and color space) for
  32507. * the given target has changed.
  32508. *
  32509. * @param {Texture} outputTarget - The output target.
  32510. * @return {Boolean} Whether the output configuration has changed or not.
  32511. */
  32512. hasOutputChange( outputTarget ) {
  32513. const cacheKey = _outputNodeMap.get( outputTarget );
  32514. return cacheKey !== this.getOutputCacheKey();
  32515. }
  32516. /**
  32517. * Returns a node that represents the output configuration (tone mapping and
  32518. * color space) for the current target.
  32519. *
  32520. * @param {Texture} outputTarget - The output target.
  32521. * @return {Node} The output node.
  32522. */
  32523. getOutputNode( outputTarget ) {
  32524. const renderer = this.renderer;
  32525. const cacheKey = this.getOutputCacheKey();
  32526. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32527. _outputNodeMap.set( outputTarget, cacheKey );
  32528. return output;
  32529. }
  32530. /**
  32531. * Triggers the call of `updateBefore()` methods
  32532. * for all nodes of the given render object.
  32533. *
  32534. * @param {RenderObject} renderObject - The render object.
  32535. */
  32536. updateBefore( renderObject ) {
  32537. const nodeBuilder = renderObject.getNodeBuilderState();
  32538. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32539. // update frame state for each node
  32540. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32541. }
  32542. }
  32543. /**
  32544. * Triggers the call of `updateAfter()` methods
  32545. * for all nodes of the given render object.
  32546. *
  32547. * @param {RenderObject} renderObject - The render object.
  32548. */
  32549. updateAfter( renderObject ) {
  32550. const nodeBuilder = renderObject.getNodeBuilderState();
  32551. for ( const node of nodeBuilder.updateAfterNodes ) {
  32552. // update frame state for each node
  32553. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32554. }
  32555. }
  32556. /**
  32557. * Triggers the call of `update()` methods
  32558. * for all nodes of the given compute node.
  32559. *
  32560. * @param {Node} computeNode - The compute node.
  32561. */
  32562. updateForCompute( computeNode ) {
  32563. const nodeFrame = this.getNodeFrame();
  32564. const nodeBuilder = this.getForCompute( computeNode );
  32565. for ( const node of nodeBuilder.updateNodes ) {
  32566. nodeFrame.updateNode( node );
  32567. }
  32568. }
  32569. /**
  32570. * Triggers the call of `update()` methods
  32571. * for all nodes of the given compute node.
  32572. *
  32573. * @param {RenderObject} renderObject - The render object.
  32574. */
  32575. updateForRender( renderObject ) {
  32576. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32577. const nodeBuilder = renderObject.getNodeBuilderState();
  32578. for ( const node of nodeBuilder.updateNodes ) {
  32579. nodeFrame.updateNode( node );
  32580. }
  32581. }
  32582. /**
  32583. * Returns `true` if the given render object requires a refresh.
  32584. *
  32585. * @param {RenderObject} renderObject - The render object.
  32586. * @return {Boolean} Whether the given render object requires a refresh or not.
  32587. */
  32588. needsRefresh( renderObject ) {
  32589. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32590. const monitor = renderObject.getMonitor();
  32591. return monitor.needsRefresh( renderObject, nodeFrame );
  32592. }
  32593. /**
  32594. * Frees the internal resources.
  32595. */
  32596. dispose() {
  32597. super.dispose();
  32598. this.nodeFrame = new NodeFrame();
  32599. this.nodeBuilderCache = new Map();
  32600. this.cacheLib = {};
  32601. }
  32602. }
  32603. const _plane = /*@__PURE__*/ new Plane();
  32604. /**
  32605. * Represents the state that is used to perform clipping via clipping planes.
  32606. * There is a default clipping context for each render context. When the
  32607. * scene holds instances of `ClippingGroup`, there will be a context for each
  32608. * group.
  32609. *
  32610. * @private
  32611. */
  32612. class ClippingContext {
  32613. /**
  32614. * Constructs a new clipping context.
  32615. *
  32616. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32617. */
  32618. constructor( parentContext = null ) {
  32619. /**
  32620. * The clipping context's version.
  32621. *
  32622. * @type {Number}
  32623. * @readonly
  32624. */
  32625. this.version = 0;
  32626. /**
  32627. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32628. *
  32629. * @type {Boolean?}
  32630. * @default null
  32631. */
  32632. this.clipIntersection = null;
  32633. /**
  32634. * The clipping context's cache key.
  32635. *
  32636. * @type {String}
  32637. */
  32638. this.cacheKey = '';
  32639. /**
  32640. * Whether the shadow pass is active or not.
  32641. *
  32642. * @type {Boolean}
  32643. * @default false
  32644. */
  32645. this.shadowPass = false;
  32646. /**
  32647. * The view normal matrix.
  32648. *
  32649. * @type {Matrix3}
  32650. */
  32651. this.viewNormalMatrix = new Matrix3();
  32652. /**
  32653. * Internal cache for maintaining clipping contexts.
  32654. *
  32655. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32656. */
  32657. this.clippingGroupContexts = new WeakMap();
  32658. /**
  32659. * The intersection planes.
  32660. *
  32661. * @type {Array<Vector4>}
  32662. */
  32663. this.intersectionPlanes = [];
  32664. /**
  32665. * The intersection planes.
  32666. *
  32667. * @type {Array<Vector4>}
  32668. */
  32669. this.unionPlanes = [];
  32670. /**
  32671. * The version of the clipping context's parent context.
  32672. *
  32673. * @type {Number?}
  32674. * @readonly
  32675. */
  32676. this.parentVersion = null;
  32677. if ( parentContext !== null ) {
  32678. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32679. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32680. this.shadowPass = parentContext.shadowPass;
  32681. this.viewMatrix = parentContext.viewMatrix;
  32682. }
  32683. }
  32684. /**
  32685. * Projects the given source clipping planes and writes the result into the
  32686. * destination array.
  32687. *
  32688. * @param {Array<Plane>} source - The source clipping planes.
  32689. * @param {Array<Vector4>} destination - The destination.
  32690. * @param {Number} offset - The offset.
  32691. */
  32692. projectPlanes( source, destination, offset ) {
  32693. const l = source.length;
  32694. for ( let i = 0; i < l; i ++ ) {
  32695. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32696. const v = destination[ offset + i ];
  32697. const normal = _plane.normal;
  32698. v.x = - normal.x;
  32699. v.y = - normal.y;
  32700. v.z = - normal.z;
  32701. v.w = _plane.constant;
  32702. }
  32703. }
  32704. /**
  32705. * Updates the root clipping context of a scene.
  32706. *
  32707. * @param {Scene} scene - The scene.
  32708. * @param {Camera} camera - The camera that is used to render the scene.
  32709. */
  32710. updateGlobal( scene, camera ) {
  32711. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32712. this.viewMatrix = camera.matrixWorldInverse;
  32713. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32714. }
  32715. /**
  32716. * Updates the clipping context.
  32717. *
  32718. * @param {ClippingContext} parentContext - The parent context.
  32719. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32720. */
  32721. update( parentContext, clippingGroup ) {
  32722. let update = false;
  32723. if ( parentContext.version !== this.parentVersion ) {
  32724. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32725. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32726. this.parentVersion = parentContext.version;
  32727. }
  32728. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32729. this.clipIntersection = clippingGroup.clipIntersection;
  32730. if ( this.clipIntersection ) {
  32731. this.unionPlanes.length = parentContext.unionPlanes.length;
  32732. } else {
  32733. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32734. }
  32735. }
  32736. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32737. const l = srcClippingPlanes.length;
  32738. let dstClippingPlanes;
  32739. let offset;
  32740. if ( this.clipIntersection ) {
  32741. dstClippingPlanes = this.intersectionPlanes;
  32742. offset = parentContext.intersectionPlanes.length;
  32743. } else {
  32744. dstClippingPlanes = this.unionPlanes;
  32745. offset = parentContext.unionPlanes.length;
  32746. }
  32747. if ( dstClippingPlanes.length !== offset + l ) {
  32748. dstClippingPlanes.length = offset + l;
  32749. for ( let i = 0; i < l; i ++ ) {
  32750. dstClippingPlanes[ offset + i ] = new Vector4();
  32751. }
  32752. update = true;
  32753. }
  32754. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32755. if ( update ) {
  32756. this.version ++;
  32757. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32758. }
  32759. }
  32760. /**
  32761. * Returns a clipping context for the given clipping group.
  32762. *
  32763. * @param {ClippingGroup} clippingGroup - The clipping group.
  32764. * @return {ClippingContext} The clipping context.
  32765. */
  32766. getGroupContext( clippingGroup ) {
  32767. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32768. let context = this.clippingGroupContexts.get( clippingGroup );
  32769. if ( context === undefined ) {
  32770. context = new ClippingContext( this );
  32771. this.clippingGroupContexts.set( clippingGroup, context );
  32772. }
  32773. context.update( this, clippingGroup );
  32774. return context;
  32775. }
  32776. /**
  32777. * The count of union clipping planes.
  32778. *
  32779. * @type {Number}
  32780. * @readonly
  32781. */
  32782. get unionClippingCount() {
  32783. return this.unionPlanes.length;
  32784. }
  32785. }
  32786. /**
  32787. * This module is used to represent render bundles inside the renderer
  32788. * for further processing.
  32789. *
  32790. * @private
  32791. */
  32792. class RenderBundle {
  32793. /**
  32794. * Constructs a new bundle group.
  32795. *
  32796. * @param {BundleGroup} bundleGroup - The bundle group.
  32797. * @param {Camera} camera - The camera the bundle group is rendered with.
  32798. */
  32799. constructor( bundleGroup, camera ) {
  32800. this.bundleGroup = bundleGroup;
  32801. this.camera = camera;
  32802. }
  32803. }
  32804. const _chainKeys$1 = [];
  32805. /**
  32806. * This renderer module manages render bundles.
  32807. *
  32808. * @private
  32809. */
  32810. class RenderBundles {
  32811. /**
  32812. * Constructs a new render bundle management component.
  32813. */
  32814. constructor() {
  32815. /**
  32816. * A chain map for maintaining the render bundles.
  32817. *
  32818. * @type {ChainMap}
  32819. */
  32820. this.bundles = new ChainMap();
  32821. }
  32822. /**
  32823. * Returns a render bundle for the given bundle group and camera.
  32824. *
  32825. * @param {BundleGroup} bundleGroup - The bundle group.
  32826. * @param {Camera} camera - The camera the bundle group is rendered with.
  32827. * @return {RenderBundle} The render bundle.
  32828. */
  32829. get( bundleGroup, camera ) {
  32830. const bundles = this.bundles;
  32831. _chainKeys$1[ 0 ] = bundleGroup;
  32832. _chainKeys$1[ 1 ] = camera;
  32833. let bundle = bundles.get( _chainKeys$1 );
  32834. if ( bundle === undefined ) {
  32835. bundle = new RenderBundle( bundleGroup, camera );
  32836. bundles.set( _chainKeys$1, bundle );
  32837. }
  32838. _chainKeys$1.length = 0;
  32839. return bundle;
  32840. }
  32841. /**
  32842. * Frees all internal resources.
  32843. */
  32844. dispose() {
  32845. this.bundles = new ChainMap();
  32846. }
  32847. }
  32848. /**
  32849. * The purpose of a node library is to assign node implementations
  32850. * to existing library features. In `WebGPURenderer` lights, materials
  32851. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32852. * are implemented with node-based modules.
  32853. *
  32854. * @private
  32855. */
  32856. class NodeLibrary {
  32857. /**
  32858. * Constructs a new node library.
  32859. */
  32860. constructor() {
  32861. /**
  32862. * A weak map that maps lights to light nodes.
  32863. *
  32864. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32865. */
  32866. this.lightNodes = new WeakMap();
  32867. /**
  32868. * A map that maps materials to node materials.
  32869. *
  32870. * @type {Map<String,NodeMaterial.constructor>}
  32871. */
  32872. this.materialNodes = new Map();
  32873. /**
  32874. * A map that maps tone mapping techniques (constants)
  32875. * to tone mapping node functions.
  32876. *
  32877. * @type {Map<Number,Function>}
  32878. */
  32879. this.toneMappingNodes = new Map();
  32880. }
  32881. /**
  32882. * Returns a matching node material instance for the given material object.
  32883. *
  32884. * This method also assigns/copies the properties of the given material object
  32885. * to the node material. This is done to make sure the current material
  32886. * configuration carries over to the node version.
  32887. *
  32888. * @param {Material} material - A material.
  32889. * @return {NodeMaterial} The corresponding node material.
  32890. */
  32891. fromMaterial( material ) {
  32892. if ( material.isNodeMaterial ) return material;
  32893. let nodeMaterial = null;
  32894. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32895. if ( nodeMaterialClass !== null ) {
  32896. nodeMaterial = new nodeMaterialClass();
  32897. for ( const key in material ) {
  32898. nodeMaterial[ key ] = material[ key ];
  32899. }
  32900. }
  32901. return nodeMaterial;
  32902. }
  32903. /**
  32904. * Adds a tone mapping node function for a tone mapping technique (constant).
  32905. *
  32906. * @param {Function} toneMappingNode - The tone mapping node function.
  32907. * @param {Number} toneMapping - The tone mapping.
  32908. */
  32909. addToneMapping( toneMappingNode, toneMapping ) {
  32910. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32911. }
  32912. /**
  32913. * Returns a tone mapping node function for a tone mapping technique (constant).
  32914. *
  32915. * @param {Number} toneMapping - The tone mapping.
  32916. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32917. */
  32918. getToneMappingFunction( toneMapping ) {
  32919. return this.toneMappingNodes.get( toneMapping ) || null;
  32920. }
  32921. /**
  32922. * Returns a node material class definition for a material type.
  32923. *
  32924. * @param {String} materialType - The material type.
  32925. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32926. */
  32927. getMaterialNodeClass( materialType ) {
  32928. return this.materialNodes.get( materialType ) || null;
  32929. }
  32930. /**
  32931. * Adds a node material class definition for a given material type.
  32932. *
  32933. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32934. * @param {String} materialClassType - The material type.
  32935. */
  32936. addMaterial( materialNodeClass, materialClassType ) {
  32937. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32938. }
  32939. /**
  32940. * Returns a light node class definition for a light class definition.
  32941. *
  32942. * @param {Light.constructor} light - The light class definition.
  32943. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32944. */
  32945. getLightNodeClass( light ) {
  32946. return this.lightNodes.get( light ) || null;
  32947. }
  32948. /**
  32949. * Adds a light node class definition for a given light class definition.
  32950. *
  32951. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32952. * @param {Light.constructor} lightClass - The light class definition.
  32953. */
  32954. addLight( lightNodeClass, lightClass ) {
  32955. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32956. }
  32957. /**
  32958. * Adds a node class definition for the given type to the provided type library.
  32959. *
  32960. * @param {Any} nodeClass - The node class definition.
  32961. * @param {Number|String} type - The object type.
  32962. * @param {Map} library - The type library.
  32963. */
  32964. addType( nodeClass, type, library ) {
  32965. if ( library.has( type ) ) {
  32966. console.warn( `Redefinition of node ${ type }` );
  32967. return;
  32968. }
  32969. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32970. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32971. library.set( type, nodeClass );
  32972. }
  32973. /**
  32974. * Adds a node class definition for the given class definition to the provided type library.
  32975. *
  32976. * @param {Any} nodeClass - The node class definition.
  32977. * @param {Any} baseClass - The class definition.
  32978. * @param {WeakMap} library - The type library.
  32979. */
  32980. addClass( nodeClass, baseClass, library ) {
  32981. if ( library.has( baseClass ) ) {
  32982. console.warn( `Redefinition of node ${ baseClass.name }` );
  32983. return;
  32984. }
  32985. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32986. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32987. library.set( baseClass, nodeClass );
  32988. }
  32989. }
  32990. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32991. const _chainKeys = [];
  32992. /**
  32993. * This renderer module manages the lights nodes which are unique
  32994. * per scene and camera combination.
  32995. *
  32996. * The lights node itself is later configured in the render list
  32997. * with the actual lights from the scene.
  32998. *
  32999. * @private
  33000. * @augments ChainMap
  33001. */
  33002. class Lighting extends ChainMap {
  33003. /**
  33004. * Constructs a lighting management component.
  33005. */
  33006. constructor() {
  33007. super();
  33008. }
  33009. /**
  33010. * Creates a new lights node for the given array of lights.
  33011. *
  33012. * @param {Array<Light>} lights - The render object.
  33013. * @return {LightsNode} The lights node.
  33014. */
  33015. createNode( lights = [] ) {
  33016. return new LightsNode().setLights( lights );
  33017. }
  33018. /**
  33019. * Returns a lights node for the given scene and camera.
  33020. *
  33021. * @param {Scene} scene - The scene.
  33022. * @param {Camera} camera - The camera.
  33023. * @return {LightsNode} The lights node.
  33024. */
  33025. getNode( scene, camera ) {
  33026. // ignore post-processing
  33027. if ( scene.isQuadMesh ) return _defaultLights;
  33028. _chainKeys[ 0 ] = scene;
  33029. _chainKeys[ 1 ] = camera;
  33030. let node = this.get( _chainKeys );
  33031. if ( node === undefined ) {
  33032. node = this.createNode();
  33033. this.set( _chainKeys, node );
  33034. }
  33035. _chainKeys.length = 0;
  33036. return node;
  33037. }
  33038. }
  33039. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33040. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33041. /**
  33042. * The XR manager is built on top of the WebXR Device API to
  33043. * manage XR sessions with `WebGPURenderer`.
  33044. *
  33045. * XR is currently only supported with a WebGL 2 backend.
  33046. *
  33047. * @augments EventDispatcher
  33048. */
  33049. class XRManager extends EventDispatcher {
  33050. /**
  33051. * Constructs a new XR manager.
  33052. *
  33053. * @param {Renderer} renderer - The renderer.
  33054. */
  33055. constructor( renderer ) {
  33056. super();
  33057. /**
  33058. * This flag globally enables XR rendering.
  33059. *
  33060. * @type {Boolean}
  33061. * @default false
  33062. */
  33063. this.enabled = false;
  33064. /**
  33065. * Whether the XR device is currently presenting or not.
  33066. *
  33067. * @type {Boolean}
  33068. * @default false
  33069. * @readonly
  33070. */
  33071. this.isPresenting = false;
  33072. /**
  33073. * Whether the XR camera should automatically be updated or not.
  33074. *
  33075. * @type {Boolean}
  33076. * @default true
  33077. */
  33078. this.cameraAutoUpdate = true;
  33079. /**
  33080. * The renderer.
  33081. *
  33082. * @private
  33083. * @type {Renderer}
  33084. */
  33085. this._renderer = renderer;
  33086. // camera
  33087. /**
  33088. * Represents the camera for the left eye.
  33089. *
  33090. * @private
  33091. * @type {PerspectiveCamera}
  33092. */
  33093. this._cameraL = new PerspectiveCamera();
  33094. this._cameraL.viewport = new Vector4();
  33095. /**
  33096. * Represents the camera for the right eye.
  33097. *
  33098. * @private
  33099. * @type {PerspectiveCamera}
  33100. */
  33101. this._cameraR = new PerspectiveCamera();
  33102. this._cameraR.viewport = new Vector4();
  33103. /**
  33104. * A list of cameras used for rendering the XR views.
  33105. *
  33106. * @private
  33107. * @type {Array<Camera>}
  33108. */
  33109. this._cameras = [ this._cameraL, this._cameraR ];
  33110. /**
  33111. * The main XR camera.
  33112. *
  33113. * @private
  33114. * @type {ArrayCamera}
  33115. */
  33116. this._cameraXR = new ArrayCamera();
  33117. /**
  33118. * The current near value of the XR camera.
  33119. *
  33120. * @private
  33121. * @type {Number?}
  33122. * @default null
  33123. */
  33124. this._currentDepthNear = null;
  33125. /**
  33126. * The current far value of the XR camera.
  33127. *
  33128. * @private
  33129. * @type {Number?}
  33130. * @default null
  33131. */
  33132. this._currentDepthFar = null;
  33133. /**
  33134. * A list of WebXR controllers requested by the application.
  33135. *
  33136. * @private
  33137. * @type {Array<WebXRController>}
  33138. */
  33139. this._controllers = [];
  33140. /**
  33141. * A list of XR input source. Each input source belongs to
  33142. * an instance of WebXRController.
  33143. *
  33144. * @private
  33145. * @type {Array<XRInputSource?>}
  33146. */
  33147. this._controllerInputSources = [];
  33148. /**
  33149. * The current render target of the renderer.
  33150. *
  33151. * @private
  33152. * @type {RenderTarget?}
  33153. * @default null
  33154. */
  33155. this._currentRenderTarget = null;
  33156. /**
  33157. * The XR render target that represents the rendering destination
  33158. * during an active XR session.
  33159. *
  33160. * @private
  33161. * @type {RenderTarget?}
  33162. * @default null
  33163. */
  33164. this._xrRenderTarget = null;
  33165. /**
  33166. * The current animation context.
  33167. *
  33168. * @private
  33169. * @type {Window?}
  33170. * @default null
  33171. */
  33172. this._currentAnimationContext = null;
  33173. /**
  33174. * The current animation loop.
  33175. *
  33176. * @private
  33177. * @type {Function?}
  33178. * @default null
  33179. */
  33180. this._currentAnimationLoop = null;
  33181. /**
  33182. * The current pixel ratio.
  33183. *
  33184. * @private
  33185. * @type {Number?}
  33186. * @default null
  33187. */
  33188. this._currentPixelRatio = null;
  33189. /**
  33190. * The current size of the renderer's canvas
  33191. * in logical pixel unit.
  33192. *
  33193. * @private
  33194. * @type {Vector2}
  33195. */
  33196. this._currentSize = new Vector2();
  33197. /**
  33198. * The default event listener for handling events inside a XR session.
  33199. *
  33200. * @private
  33201. * @type {Function}
  33202. */
  33203. this._onSessionEvent = onSessionEvent.bind( this );
  33204. /**
  33205. * The event listener for handling the end of a XR session.
  33206. *
  33207. * @private
  33208. * @type {Function}
  33209. */
  33210. this._onSessionEnd = onSessionEnd.bind( this );
  33211. /**
  33212. * The event listener for handling the `inputsourceschange` event.
  33213. *
  33214. * @private
  33215. * @type {Function}
  33216. */
  33217. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33218. /**
  33219. * The animation loop which is used as a replacement for the default
  33220. * animation loop of the applicatio. It is only used when a XR session
  33221. * is active.
  33222. *
  33223. * @private
  33224. * @type {Function}
  33225. */
  33226. this._onAnimationFrame = onAnimationFrame.bind( this );
  33227. /**
  33228. * The current XR reference space.
  33229. *
  33230. * @private
  33231. * @type {XRReferenceSpace?}
  33232. * @default null
  33233. */
  33234. this._referenceSpace = null;
  33235. /**
  33236. * The current XR reference space type.
  33237. *
  33238. * @private
  33239. * @type {String}
  33240. * @default 'local-floor'
  33241. */
  33242. this._referenceSpaceType = 'local-floor';
  33243. /**
  33244. * A custom reference space defined by the application.
  33245. *
  33246. * @private
  33247. * @type {XRReferenceSpace?}
  33248. * @default null
  33249. */
  33250. this._customReferenceSpace = null;
  33251. /**
  33252. * The framebuffer scale factor.
  33253. *
  33254. * @private
  33255. * @type {Number}
  33256. * @default 1
  33257. */
  33258. this._framebufferScaleFactor = 1;
  33259. /**
  33260. * The foveation factor.
  33261. *
  33262. * @private
  33263. * @type {Number}
  33264. * @default 1
  33265. */
  33266. this._foveation = 1.0;
  33267. /**
  33268. * A reference to the current XR session.
  33269. *
  33270. * @private
  33271. * @type {XRSession?}
  33272. * @default null
  33273. */
  33274. this._session = null;
  33275. /**
  33276. * A reference to the current XR base layer.
  33277. *
  33278. * @private
  33279. * @type {XRWebGLLayer?}
  33280. * @default null
  33281. */
  33282. this._glBaseLayer = null;
  33283. /**
  33284. * A reference to the current XR binding.
  33285. *
  33286. * @private
  33287. * @type {XRWebGLBinding?}
  33288. * @default null
  33289. */
  33290. this._glBinding = null;
  33291. /**
  33292. * A reference to the current XR projection layer.
  33293. *
  33294. * @private
  33295. * @type {XRProjectionLayer?}
  33296. * @default null
  33297. */
  33298. this._glProjLayer = null;
  33299. /**
  33300. * A reference to the current XR frame.
  33301. *
  33302. * @private
  33303. * @type {XRFrame?}
  33304. * @default null
  33305. */
  33306. this._xrFrame = null;
  33307. /**
  33308. * Whether to use projection layers or not.
  33309. *
  33310. * @private
  33311. * @type {Boolean}
  33312. * @readonly
  33313. */
  33314. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  33315. }
  33316. /**
  33317. * Returns an instance of `THREE.Group` that represents the transformation
  33318. * of a XR controller in target ray space. The requested controller is defined
  33319. * by the given index.
  33320. *
  33321. * @param {Number} index - The index of the XR controller.
  33322. * @return {Group} A group that represents the controller's transformation.
  33323. */
  33324. getController( index ) {
  33325. const controller = this._getController( index );
  33326. return controller.getTargetRaySpace();
  33327. }
  33328. /**
  33329. * Returns an instance of `THREE.Group` that represents the transformation
  33330. * of a XR controller in grip space. The requested controller is defined
  33331. * by the given index.
  33332. *
  33333. * @param {Number} index - The index of the XR controller.
  33334. * @return {Group} A group that represents the controller's transformation.
  33335. */
  33336. getControllerGrip( index ) {
  33337. const controller = this._getController( index );
  33338. return controller.getGripSpace();
  33339. }
  33340. /**
  33341. * Returns an instance of `THREE.Group` that represents the transformation
  33342. * of a XR controller in hand space. The requested controller is defined
  33343. * by the given index.
  33344. *
  33345. * @param {Number} index - The index of the XR controller.
  33346. * @return {Group} A group that represents the controller's transformation.
  33347. */
  33348. getHand( index ) {
  33349. const controller = this._getController( index );
  33350. return controller.getHandSpace();
  33351. }
  33352. /**
  33353. * Returns the foveation value.
  33354. *
  33355. * @return {Number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  33356. */
  33357. getFoveation() {
  33358. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  33359. return undefined;
  33360. }
  33361. return this._foveation;
  33362. }
  33363. /**
  33364. * Sets the foveation value.
  33365. *
  33366. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33367. * and `1` means maximum foveation (the edges render at lower resolution).
  33368. */
  33369. setFoveation( foveation ) {
  33370. this._foveation = foveation;
  33371. if ( this._glProjLayer !== null ) {
  33372. this._glProjLayer.fixedFoveation = foveation;
  33373. }
  33374. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33375. this._glBaseLayer.fixedFoveation = foveation;
  33376. }
  33377. }
  33378. /**
  33379. * Returns the framebuffer scale factor.
  33380. *
  33381. * @return {Number} The framebuffer scale factor.
  33382. */
  33383. getFramebufferScaleFactor() {
  33384. return this._framebufferScaleFactor;
  33385. }
  33386. /**
  33387. * Sets the framebuffer scale factor.
  33388. *
  33389. * This method can not be used during a XR session.
  33390. *
  33391. * @param {Number} factor - The framebuffer scale factor.
  33392. */
  33393. setFramebufferScaleFactor( factor ) {
  33394. this._framebufferScaleFactor = factor;
  33395. if ( this.isPresenting === true ) {
  33396. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33397. }
  33398. }
  33399. /**
  33400. * Returns the reference space type.
  33401. *
  33402. * @return {String} The reference space type.
  33403. */
  33404. getReferenceSpaceType() {
  33405. return this._referenceSpaceType;
  33406. }
  33407. /**
  33408. * Sets the reference space type.
  33409. *
  33410. * This method can not be used during a XR session.
  33411. *
  33412. * @param {String} type - The reference space type.
  33413. */
  33414. setReferenceSpaceType( type ) {
  33415. this._referenceSpaceType = type;
  33416. if ( this.isPresenting === true ) {
  33417. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33418. }
  33419. }
  33420. /**
  33421. * Returns the XR reference space.
  33422. *
  33423. * @return {XRReferenceSpace} The XR reference space.
  33424. */
  33425. getReferenceSpace() {
  33426. return this._customReferenceSpace || this._referenceSpace;
  33427. }
  33428. /**
  33429. * Sets a custom XR reference space.
  33430. *
  33431. * @param {XRReferenceSpace} space - The XR reference space.
  33432. */
  33433. setReferenceSpace( space ) {
  33434. this._customReferenceSpace = space;
  33435. }
  33436. /**
  33437. * Returns the XR camera.
  33438. *
  33439. * @return {ArrayCamera} The XR camera.
  33440. */
  33441. getCamera() {
  33442. return this._cameraXR;
  33443. }
  33444. /**
  33445. * Returns the environment blend mode from the current XR session.
  33446. *
  33447. * @return {('opaque'|'additive'|'alpha-blend')?} The environment blend mode. Returns `null` when used outside of a XR session.
  33448. */
  33449. getEnvironmentBlendMode() {
  33450. if ( this._session !== null ) {
  33451. return this._session.environmentBlendMode;
  33452. }
  33453. }
  33454. /**
  33455. * Returns the current XR frame.
  33456. *
  33457. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  33458. */
  33459. getFrame() {
  33460. return this._xrFrame;
  33461. }
  33462. /**
  33463. * Returns the current XR session.
  33464. *
  33465. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  33466. */
  33467. getSession() {
  33468. return this._session;
  33469. }
  33470. /**
  33471. * After a XR session has been requested usually with one of the `*Button` modules, it
  33472. * is injected into the renderer with this method. This method triggers the start of
  33473. * the actual XR rendering.
  33474. *
  33475. * @async
  33476. * @param {XRSession} session - The XR session to set.
  33477. * @return {Promise} A Promise that resolves when the session has been set.
  33478. */
  33479. async setSession( session ) {
  33480. const renderer = this._renderer;
  33481. const backend = renderer.backend;
  33482. const gl = renderer.getContext();
  33483. this._session = session;
  33484. if ( session !== null ) {
  33485. 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.' );
  33486. this._currentRenderTarget = renderer.getRenderTarget();
  33487. session.addEventListener( 'select', this._onSessionEvent );
  33488. session.addEventListener( 'selectstart', this._onSessionEvent );
  33489. session.addEventListener( 'selectend', this._onSessionEvent );
  33490. session.addEventListener( 'squeeze', this._onSessionEvent );
  33491. session.addEventListener( 'squeezestart', this._onSessionEvent );
  33492. session.addEventListener( 'squeezeend', this._onSessionEvent );
  33493. session.addEventListener( 'end', this._onSessionEnd );
  33494. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33495. await backend.makeXRCompatible();
  33496. this._currentPixelRatio = renderer.getPixelRatio();
  33497. renderer.getSize( this._currentSize );
  33498. this._currentAnimationContext = renderer._animation.getContext();
  33499. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  33500. renderer._animation.stop();
  33501. //
  33502. const attributes = gl.getContextAttributes();
  33503. if ( this._useLayers === true ) {
  33504. // default path using XRWebGLBinding/XRProjectionLayer
  33505. let depthFormat = null;
  33506. let depthType = null;
  33507. let glDepthFormat = null;
  33508. if ( attributes.depth ) {
  33509. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  33510. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  33511. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  33512. }
  33513. const projectionlayerInit = {
  33514. colorFormat: gl.RGBA8,
  33515. depthFormat: glDepthFormat,
  33516. scaleFactor: this._framebufferScaleFactor
  33517. };
  33518. const glBinding = new XRWebGLBinding( session, gl );
  33519. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  33520. this._glBinding = glBinding;
  33521. this._glProjLayer = glProjLayer;
  33522. session.updateRenderState( { layers: [ glProjLayer ] } );
  33523. renderer.setPixelRatio( 1 );
  33524. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  33525. this._xrRenderTarget = new RenderTarget(
  33526. glProjLayer.textureWidth,
  33527. glProjLayer.textureHeight,
  33528. {
  33529. format: RGBAFormat,
  33530. type: UnsignedByteType,
  33531. colorSpace: renderer.outputColorSpace,
  33532. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  33533. stencilBuffer: attributes.stencil
  33534. } );
  33535. this._xrRenderTarget.hasExternalTextures = true;
  33536. } else {
  33537. // fallback to XRWebGLLayer
  33538. const layerInit = {
  33539. antialias: attributes.antialias,
  33540. alpha: true,
  33541. depth: attributes.depth,
  33542. stencil: attributes.stencil,
  33543. framebufferScaleFactor: this.getFramebufferScaleFactor()
  33544. };
  33545. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  33546. this._glBaseLayer = glBaseLayer;
  33547. session.updateRenderState( { baseLayer: glBaseLayer } );
  33548. renderer.setPixelRatio( 1 );
  33549. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  33550. this._xrRenderTarget = new RenderTarget(
  33551. glBaseLayer.framebufferWidth,
  33552. glBaseLayer.framebufferHeight,
  33553. {
  33554. format: RGBAFormat,
  33555. type: UnsignedByteType,
  33556. colorSpace: renderer.outputColorSpace,
  33557. stencilBuffer: attributes.stencil
  33558. }
  33559. );
  33560. }
  33561. this._xrRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  33562. //
  33563. this.setFoveation( this.getFoveation() );
  33564. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  33565. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  33566. renderer._animation.setContext( session );
  33567. renderer._animation.start();
  33568. this.isPresenting = true;
  33569. this.dispatchEvent( { type: 'sessionstart' } );
  33570. }
  33571. }
  33572. /**
  33573. * This method is called by the renderer per frame and updates the XR camera
  33574. * and it sub cameras based on the given camera. The given camera is the "user"
  33575. * camera created on application level and used for non-XR rendering.
  33576. *
  33577. * @param {PerspectiveCamera} camera - The camera.
  33578. */
  33579. updateCamera( camera ) {
  33580. const session = this._session;
  33581. if ( session === null ) return;
  33582. const depthNear = camera.near;
  33583. const depthFar = camera.far;
  33584. const cameraXR = this._cameraXR;
  33585. const cameraL = this._cameraL;
  33586. const cameraR = this._cameraR;
  33587. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  33588. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  33589. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  33590. // Note that the new renderState won't apply until the next frame. See #18320
  33591. session.updateRenderState( {
  33592. depthNear: cameraXR.near,
  33593. depthFar: cameraXR.far
  33594. } );
  33595. this._currentDepthNear = cameraXR.near;
  33596. this._currentDepthFar = cameraXR.far;
  33597. }
  33598. cameraL.layers.mask = camera.layers.mask | 0b010;
  33599. cameraR.layers.mask = camera.layers.mask | 0b100;
  33600. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  33601. const parent = camera.parent;
  33602. const cameras = cameraXR.cameras;
  33603. updateCamera( cameraXR, parent );
  33604. for ( let i = 0; i < cameras.length; i ++ ) {
  33605. updateCamera( cameras[ i ], parent );
  33606. }
  33607. // update projection matrix for proper view frustum culling
  33608. if ( cameras.length === 2 ) {
  33609. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  33610. } else {
  33611. // assume single camera setup (AR)
  33612. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  33613. }
  33614. // update user camera and its children
  33615. updateUserCamera( camera, cameraXR, parent );
  33616. }
  33617. /**
  33618. * Returns a WebXR controller for the given controller index.
  33619. *
  33620. * @private
  33621. * @param {Number} index - The controller index.
  33622. * @return {WebXRController} The XR controller.
  33623. */
  33624. _getController( index ) {
  33625. let controller = this._controllers[ index ];
  33626. if ( controller === undefined ) {
  33627. controller = new WebXRController();
  33628. this._controllers[ index ] = controller;
  33629. }
  33630. return controller;
  33631. }
  33632. }
  33633. /**
  33634. * Assumes 2 cameras that are parallel and share an X-axis, and that
  33635. * the cameras' projection and world matrices have already been set.
  33636. * And that near and far planes are identical for both cameras.
  33637. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  33638. *
  33639. * @param {ArrayCamera} camera - The camera to update.
  33640. * @param {PerspectiveCamera} cameraL - The left camera.
  33641. * @param {PerspectiveCamera} cameraR - The right camera.
  33642. */
  33643. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  33644. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  33645. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  33646. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  33647. const projL = cameraL.projectionMatrix.elements;
  33648. const projR = cameraR.projectionMatrix.elements;
  33649. // VR systems will have identical far and near planes, and
  33650. // most likely identical top and bottom frustum extents.
  33651. // Use the left camera for these values.
  33652. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  33653. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  33654. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  33655. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  33656. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  33657. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  33658. const left = near * leftFov;
  33659. const right = near * rightFov;
  33660. // Calculate the new camera's position offset from the
  33661. // left camera. xOffset should be roughly half `ipd`.
  33662. const zOffset = ipd / ( - leftFov + rightFov );
  33663. const xOffset = zOffset * - leftFov;
  33664. // TODO: Better way to apply this offset?
  33665. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  33666. camera.translateX( xOffset );
  33667. camera.translateZ( zOffset );
  33668. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  33669. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33670. // Check if the projection uses an infinite far plane.
  33671. if ( projL[ 10 ] === -1 ) {
  33672. // Use the projection matrix from the left eye.
  33673. // The camera offset is sufficient to include the view volumes
  33674. // of both eyes (assuming symmetric projections).
  33675. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  33676. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  33677. } else {
  33678. // Find the union of the frustum values of the cameras and scale
  33679. // the values so that the near plane's position does not change in world space,
  33680. // although must now be relative to the new union camera.
  33681. const near2 = near + zOffset;
  33682. const far2 = far + zOffset;
  33683. const left2 = left - xOffset;
  33684. const right2 = right + ( ipd - xOffset );
  33685. const top2 = topFov * far / far2 * near2;
  33686. const bottom2 = bottomFov * far / far2 * near2;
  33687. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  33688. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33689. }
  33690. }
  33691. /**
  33692. * Updates the world matrices for the given camera based on the parent 3D object.
  33693. *
  33694. * @inner
  33695. * @param {Camera} camera - The camera to update.
  33696. * @param {Object3D} parent - The parent 3D object.
  33697. */
  33698. function updateCamera( camera, parent ) {
  33699. if ( parent === null ) {
  33700. camera.matrixWorld.copy( camera.matrix );
  33701. } else {
  33702. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  33703. }
  33704. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33705. }
  33706. /**
  33707. * Updates the given camera with the transfomration of the XR camera and parent object.
  33708. *
  33709. * @inner
  33710. * @param {Camera} camera - The camera to update.
  33711. * @param {ArrayCamera} cameraXR - The XR camera.
  33712. * @param {Object3D} parent - The parent 3D object.
  33713. */
  33714. function updateUserCamera( camera, cameraXR, parent ) {
  33715. if ( parent === null ) {
  33716. camera.matrix.copy( cameraXR.matrixWorld );
  33717. } else {
  33718. camera.matrix.copy( parent.matrixWorld );
  33719. camera.matrix.invert();
  33720. camera.matrix.multiply( cameraXR.matrixWorld );
  33721. }
  33722. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33723. camera.updateMatrixWorld( true );
  33724. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  33725. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  33726. if ( camera.isPerspectiveCamera ) {
  33727. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  33728. camera.zoom = 1;
  33729. }
  33730. }
  33731. function onSessionEvent( event ) {
  33732. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  33733. if ( controllerIndex === -1 ) {
  33734. return;
  33735. }
  33736. const controller = this._controllers[ controllerIndex ];
  33737. if ( controller !== undefined ) {
  33738. const referenceSpace = this.getReferenceSpace();
  33739. controller.update( event.inputSource, event.frame, referenceSpace );
  33740. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  33741. }
  33742. }
  33743. function onSessionEnd() {
  33744. const session = this._session;
  33745. const renderer = this._renderer;
  33746. session.removeEventListener( 'select', this._onSessionEvent );
  33747. session.removeEventListener( 'selectstart', this._onSessionEvent );
  33748. session.removeEventListener( 'selectend', this._onSessionEvent );
  33749. session.removeEventListener( 'squeeze', this._onSessionEvent );
  33750. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  33751. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  33752. session.removeEventListener( 'end', this._onSessionEnd );
  33753. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33754. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33755. const inputSource = this._controllerInputSources[ i ];
  33756. if ( inputSource === null ) continue;
  33757. this._controllerInputSources[ i ] = null;
  33758. this._controllers[ i ].disconnect( inputSource );
  33759. }
  33760. this._currentDepthNear = null;
  33761. this._currentDepthFar = null;
  33762. // restore framebuffer/rendering state
  33763. renderer.backend.setXRTarget( null );
  33764. renderer.setRenderTarget( this._currentRenderTarget );
  33765. this._session = null;
  33766. this._xrRenderTarget = null;
  33767. //
  33768. this.isPresenting = false;
  33769. renderer._animation.stop();
  33770. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  33771. renderer._animation.setContext( this._currentAnimationContext );
  33772. renderer._animation.start();
  33773. renderer.setPixelRatio( this._currentPixelRatio );
  33774. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  33775. this.dispatchEvent( { type: 'sessionend' } );
  33776. }
  33777. function onInputSourcesChange( event ) {
  33778. const controllers = this._controllers;
  33779. const controllerInputSources = this._controllerInputSources;
  33780. // Notify disconnected
  33781. for ( let i = 0; i < event.removed.length; i ++ ) {
  33782. const inputSource = event.removed[ i ];
  33783. const index = controllerInputSources.indexOf( inputSource );
  33784. if ( index >= 0 ) {
  33785. controllerInputSources[ index ] = null;
  33786. controllers[ index ].disconnect( inputSource );
  33787. }
  33788. }
  33789. // Notify connected
  33790. for ( let i = 0; i < event.added.length; i ++ ) {
  33791. const inputSource = event.added[ i ];
  33792. let controllerIndex = controllerInputSources.indexOf( inputSource );
  33793. if ( controllerIndex === -1 ) {
  33794. // Assign input source a controller that currently has no input source
  33795. for ( let i = 0; i < controllers.length; i ++ ) {
  33796. if ( i >= controllerInputSources.length ) {
  33797. controllerInputSources.push( inputSource );
  33798. controllerIndex = i;
  33799. break;
  33800. } else if ( controllerInputSources[ i ] === null ) {
  33801. controllerInputSources[ i ] = inputSource;
  33802. controllerIndex = i;
  33803. break;
  33804. }
  33805. }
  33806. // If all controllers do currently receive input we ignore new ones
  33807. if ( controllerIndex === -1 ) break;
  33808. }
  33809. const controller = controllers[ controllerIndex ];
  33810. if ( controller ) {
  33811. controller.connect( inputSource );
  33812. }
  33813. }
  33814. }
  33815. function onAnimationFrame( time, frame ) {
  33816. if ( frame === undefined ) return;
  33817. const cameraXR = this._cameraXR;
  33818. const renderer = this._renderer;
  33819. const backend = renderer.backend;
  33820. const glBaseLayer = this._glBaseLayer;
  33821. const referenceSpace = this.getReferenceSpace();
  33822. const pose = frame.getViewerPose( referenceSpace );
  33823. this._xrFrame = frame;
  33824. if ( pose !== null ) {
  33825. const views = pose.views;
  33826. if ( this._glBaseLayer !== null ) {
  33827. backend.setXRTarget( glBaseLayer.framebuffer );
  33828. }
  33829. let cameraXRNeedsUpdate = false;
  33830. // check if it's necessary to rebuild cameraXR's camera list
  33831. if ( views.length !== cameraXR.cameras.length ) {
  33832. cameraXR.cameras.length = 0;
  33833. cameraXRNeedsUpdate = true;
  33834. }
  33835. for ( let i = 0; i < views.length; i ++ ) {
  33836. const view = views[ i ];
  33837. let viewport;
  33838. if ( this._useLayers === true ) {
  33839. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  33840. viewport = glSubImage.viewport;
  33841. // For side-by-side projection, we only produce a single texture for both eyes.
  33842. if ( i === 0 ) {
  33843. backend.setRenderTargetTextures(
  33844. this._xrRenderTarget,
  33845. glSubImage.colorTexture,
  33846. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  33847. );
  33848. }
  33849. } else {
  33850. viewport = glBaseLayer.getViewport( view );
  33851. }
  33852. let camera = this._cameras[ i ];
  33853. if ( camera === undefined ) {
  33854. camera = new PerspectiveCamera();
  33855. camera.layers.enable( i );
  33856. camera.viewport = new Vector4();
  33857. this._cameras[ i ] = camera;
  33858. }
  33859. camera.matrix.fromArray( view.transform.matrix );
  33860. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33861. camera.projectionMatrix.fromArray( view.projectionMatrix );
  33862. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33863. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  33864. if ( i === 0 ) {
  33865. cameraXR.matrix.copy( camera.matrix );
  33866. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  33867. }
  33868. if ( cameraXRNeedsUpdate === true ) {
  33869. cameraXR.cameras.push( camera );
  33870. }
  33871. }
  33872. renderer.setRenderTarget( this._xrRenderTarget );
  33873. }
  33874. //
  33875. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33876. const inputSource = this._controllerInputSources[ i ];
  33877. const controller = this._controllers[ i ];
  33878. if ( inputSource !== null && controller !== undefined ) {
  33879. controller.update( inputSource, frame, referenceSpace );
  33880. }
  33881. }
  33882. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  33883. if ( frame.detectedPlanes ) {
  33884. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  33885. }
  33886. this._xrFrame = null;
  33887. }
  33888. /** @module Renderer **/
  33889. const _scene = /*@__PURE__*/ new Scene();
  33890. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  33891. const _screen = /*@__PURE__*/ new Vector4();
  33892. const _frustum = /*@__PURE__*/ new Frustum();
  33893. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33894. const _vector4 = /*@__PURE__*/ new Vector4();
  33895. /**
  33896. * Base class for renderers.
  33897. */
  33898. class Renderer {
  33899. /**
  33900. * Constructs a new renderer.
  33901. *
  33902. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  33903. * @param {Object} parameters - The configuration parameter.
  33904. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  33905. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  33906. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  33907. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  33908. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  33909. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  33910. * to overwrite the default.
  33911. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33912. */
  33913. constructor( backend, parameters = {} ) {
  33914. /**
  33915. * This flag can be used for type testing.
  33916. *
  33917. * @type {Boolean}
  33918. * @readonly
  33919. * @default true
  33920. */
  33921. this.isRenderer = true;
  33922. //
  33923. const {
  33924. logarithmicDepthBuffer = false,
  33925. alpha = true,
  33926. depth = true,
  33927. stencil = false,
  33928. antialias = false,
  33929. samples = 0,
  33930. getFallback = null
  33931. } = parameters;
  33932. /**
  33933. * A reference to the canvas element the renderer is drawing to.
  33934. * This value of this property will automatically be created by
  33935. * the renderer.
  33936. *
  33937. * @type {HTMLCanvasElement|OffscreenCanvas}
  33938. */
  33939. this.domElement = backend.getDomElement();
  33940. /**
  33941. * A reference to the current backend.
  33942. *
  33943. * @type {Backend}
  33944. */
  33945. this.backend = backend;
  33946. /**
  33947. * The number of MSAA samples.
  33948. *
  33949. * @type {Number}
  33950. * @default 0
  33951. */
  33952. this.samples = samples || ( antialias === true ) ? 4 : 0;
  33953. /**
  33954. * Whether the renderer should automatically clear the current rendering target
  33955. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  33956. * or the current bound render target (custom framebuffer).
  33957. *
  33958. * @type {Boolean}
  33959. * @default true
  33960. */
  33961. this.autoClear = true;
  33962. /**
  33963. * When `autoClear` is set to `true`, this property defines whether the renderer
  33964. * should clear the color buffer.
  33965. *
  33966. * @type {Boolean}
  33967. * @default true
  33968. */
  33969. this.autoClearColor = true;
  33970. /**
  33971. * When `autoClear` is set to `true`, this property defines whether the renderer
  33972. * should clear the depth buffer.
  33973. *
  33974. * @type {Boolean}
  33975. * @default true
  33976. */
  33977. this.autoClearDepth = true;
  33978. /**
  33979. * When `autoClear` is set to `true`, this property defines whether the renderer
  33980. * should clear the stencil buffer.
  33981. *
  33982. * @type {Boolean}
  33983. * @default true
  33984. */
  33985. this.autoClearStencil = true;
  33986. /**
  33987. * Whether the default framebuffer should be transparent or opaque.
  33988. *
  33989. * @type {Boolean}
  33990. * @default true
  33991. */
  33992. this.alpha = alpha;
  33993. /**
  33994. * Whether logarithmic depth buffer is enabled or not.
  33995. *
  33996. * @type {Boolean}
  33997. * @default false
  33998. */
  33999. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34000. /**
  34001. * Defines the output color space of the renderer.
  34002. *
  34003. * @type {String}
  34004. * @default SRGBColorSpace
  34005. */
  34006. this.outputColorSpace = SRGBColorSpace;
  34007. /**
  34008. * Defines the tone mapping of the renderer.
  34009. *
  34010. * @type {Number}
  34011. * @default NoToneMapping
  34012. */
  34013. this.toneMapping = NoToneMapping;
  34014. /**
  34015. * Defines the tone mapping exposure.
  34016. *
  34017. * @type {Number}
  34018. * @default 1
  34019. */
  34020. this.toneMappingExposure = 1.0;
  34021. /**
  34022. * Whether the renderer should sort its render lists or not.
  34023. *
  34024. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34025. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34026. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34027. * e.g. manually determining each object's rendering order.
  34028. *
  34029. * @type {Boolean}
  34030. * @default true
  34031. */
  34032. this.sortObjects = true;
  34033. /**
  34034. * Whether the default framebuffer should have a depth buffer or not.
  34035. *
  34036. * @type {Boolean}
  34037. * @default true
  34038. */
  34039. this.depth = depth;
  34040. /**
  34041. * Whether the default framebuffer should have a stencil buffer or not.
  34042. *
  34043. * @type {Boolean}
  34044. * @default false
  34045. */
  34046. this.stencil = stencil;
  34047. /**
  34048. * Holds a series of statistical information about the GPU memory
  34049. * and the rendering process. Useful for debugging and monitoring.
  34050. *
  34051. * @type {Info}
  34052. */
  34053. this.info = new Info();
  34054. this.nodes = {
  34055. modelViewMatrix: null,
  34056. modelNormalViewMatrix: null
  34057. };
  34058. /**
  34059. * The node library defines how certain library objects like materials, lights
  34060. * or tone mapping functions are mapped to node types. This is required since
  34061. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34062. * be part of the scene graph, they are internally represented as nodes for
  34063. * further processing.
  34064. *
  34065. * @type {NodeLibrary}
  34066. */
  34067. this.library = new NodeLibrary();
  34068. /**
  34069. * A map-like data structure for managing lights.
  34070. *
  34071. * @type {Lighting}
  34072. */
  34073. this.lighting = new Lighting();
  34074. // internals
  34075. /**
  34076. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34077. *
  34078. * @private
  34079. * @type {Function}
  34080. */
  34081. this._getFallback = getFallback;
  34082. /**
  34083. * The renderer's pixel ration.
  34084. *
  34085. * @private
  34086. * @type {Number}
  34087. * @default 1
  34088. */
  34089. this._pixelRatio = 1;
  34090. /**
  34091. * The width of the renderer's default framebuffer in logical pixel unit.
  34092. *
  34093. * @private
  34094. * @type {Number}
  34095. */
  34096. this._width = this.domElement.width;
  34097. /**
  34098. * The height of the renderer's default framebuffer in logical pixel unit.
  34099. *
  34100. * @private
  34101. * @type {Number}
  34102. */
  34103. this._height = this.domElement.height;
  34104. /**
  34105. * The viewport of the renderer in logical pixel unit.
  34106. *
  34107. * @private
  34108. * @type {Vector4}
  34109. */
  34110. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34111. /**
  34112. * The scissor rectangle of the renderer in logical pixel unit.
  34113. *
  34114. * @private
  34115. * @type {Vector4}
  34116. */
  34117. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34118. /**
  34119. * Whether the scissor test should be enabled or not.
  34120. *
  34121. * @private
  34122. * @type {Boolean}
  34123. */
  34124. this._scissorTest = false;
  34125. /**
  34126. * A reference to a renderer module for managing shader attributes.
  34127. *
  34128. * @private
  34129. * @type {Attributes?}
  34130. * @default null
  34131. */
  34132. this._attributes = null;
  34133. /**
  34134. * A reference to a renderer module for managing geometries.
  34135. *
  34136. * @private
  34137. * @type {Geometries?}
  34138. * @default null
  34139. */
  34140. this._geometries = null;
  34141. /**
  34142. * A reference to a renderer module for managing node related logic.
  34143. *
  34144. * @private
  34145. * @type {Nodes?}
  34146. * @default null
  34147. */
  34148. this._nodes = null;
  34149. /**
  34150. * A reference to a renderer module for managing the internal animation loop.
  34151. *
  34152. * @private
  34153. * @type {Animation?}
  34154. * @default null
  34155. */
  34156. this._animation = null;
  34157. /**
  34158. * A reference to a renderer module for managing shader program bindings.
  34159. *
  34160. * @private
  34161. * @type {Bindings?}
  34162. * @default null
  34163. */
  34164. this._bindings = null;
  34165. /**
  34166. * A reference to a renderer module for managing render objects.
  34167. *
  34168. * @private
  34169. * @type {RenderObjects?}
  34170. * @default null
  34171. */
  34172. this._objects = null;
  34173. /**
  34174. * A reference to a renderer module for managing render and compute pipelines.
  34175. *
  34176. * @private
  34177. * @type {Pipelines?}
  34178. * @default null
  34179. */
  34180. this._pipelines = null;
  34181. /**
  34182. * A reference to a renderer module for managing render bundles.
  34183. *
  34184. * @private
  34185. * @type {RenderBundles?}
  34186. * @default null
  34187. */
  34188. this._bundles = null;
  34189. /**
  34190. * A reference to a renderer module for managing render lists.
  34191. *
  34192. * @private
  34193. * @type {RenderLists?}
  34194. * @default null
  34195. */
  34196. this._renderLists = null;
  34197. /**
  34198. * A reference to a renderer module for managing render contexts.
  34199. *
  34200. * @private
  34201. * @type {RenderContexts?}
  34202. * @default null
  34203. */
  34204. this._renderContexts = null;
  34205. /**
  34206. * A reference to a renderer module for managing textures.
  34207. *
  34208. * @private
  34209. * @type {Textures?}
  34210. * @default null
  34211. */
  34212. this._textures = null;
  34213. /**
  34214. * A reference to a renderer module for backgrounds.
  34215. *
  34216. * @private
  34217. * @type {Background?}
  34218. * @default null
  34219. */
  34220. this._background = null;
  34221. /**
  34222. * This fullscreen quad is used for internal render passes
  34223. * like the tone mapping and color space output pass.
  34224. *
  34225. * @private
  34226. * @type {QuadMesh}
  34227. */
  34228. this._quad = new QuadMesh( new NodeMaterial() );
  34229. this._quad.material.name = 'Renderer_output';
  34230. /**
  34231. * A reference to the current render context.
  34232. *
  34233. * @private
  34234. * @type {RenderContext?}
  34235. * @default null
  34236. */
  34237. this._currentRenderContext = null;
  34238. /**
  34239. * A custom sort function for the opaque render list.
  34240. *
  34241. * @private
  34242. * @type {Function?}
  34243. * @default null
  34244. */
  34245. this._opaqueSort = null;
  34246. /**
  34247. * A custom sort function for the transparent render list.
  34248. *
  34249. * @private
  34250. * @type {Function?}
  34251. * @default null
  34252. */
  34253. this._transparentSort = null;
  34254. /**
  34255. * The framebuffer target.
  34256. *
  34257. * @private
  34258. * @type {RenderTarget?}
  34259. * @default null
  34260. */
  34261. this._frameBufferTarget = null;
  34262. const alphaClear = this.alpha === true ? 0 : 1;
  34263. /**
  34264. * The clear color value.
  34265. *
  34266. * @private
  34267. * @type {Color4}
  34268. */
  34269. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34270. /**
  34271. * The clear depth value.
  34272. *
  34273. * @private
  34274. * @type {Number}
  34275. * @default 1
  34276. */
  34277. this._clearDepth = 1;
  34278. /**
  34279. * The clear stencil value.
  34280. *
  34281. * @private
  34282. * @type {Number}
  34283. * @default 0
  34284. */
  34285. this._clearStencil = 0;
  34286. /**
  34287. * The current render target.
  34288. *
  34289. * @private
  34290. * @type {RenderTarget?}
  34291. * @default null
  34292. */
  34293. this._renderTarget = null;
  34294. /**
  34295. * The active cube face.
  34296. *
  34297. * @private
  34298. * @type {Number}
  34299. * @default 0
  34300. */
  34301. this._activeCubeFace = 0;
  34302. /**
  34303. * The active mipmap level.
  34304. *
  34305. * @private
  34306. * @type {Number}
  34307. * @default 0
  34308. */
  34309. this._activeMipmapLevel = 0;
  34310. /**
  34311. * The MRT setting.
  34312. *
  34313. * @private
  34314. * @type {MRTNode?}
  34315. * @default null
  34316. */
  34317. this._mrt = null;
  34318. /**
  34319. * This function defines how a render object is going
  34320. * to be rendered.
  34321. *
  34322. * @private
  34323. * @type {Function?}
  34324. * @default null
  34325. */
  34326. this._renderObjectFunction = null;
  34327. /**
  34328. * Used to keep track of the current render object function.
  34329. *
  34330. * @private
  34331. * @type {Function?}
  34332. * @default null
  34333. */
  34334. this._currentRenderObjectFunction = null;
  34335. /**
  34336. * Used to keep track of the current render bundle.
  34337. *
  34338. * @private
  34339. * @type {RenderBundle?}
  34340. * @default null
  34341. */
  34342. this._currentRenderBundle = null;
  34343. /**
  34344. * Next to `_renderObjectFunction()`, this function provides another hook
  34345. * for influencing the render process of a render object. It is meant for internal
  34346. * use and only relevant for `compileAsync()` right now. Instead of using
  34347. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34348. * a different function might be used which performs no draw but just the node
  34349. * and pipeline updates.
  34350. *
  34351. * @private
  34352. * @type {Function?}
  34353. * @default null
  34354. */
  34355. this._handleObjectFunction = this._renderObjectDirect;
  34356. /**
  34357. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34358. * lost is considered as a context lost. When this is set to `true`, rendering
  34359. * isn't possible anymore.
  34360. *
  34361. * @private
  34362. * @type {Boolean}
  34363. * @default false
  34364. */
  34365. this._isDeviceLost = false;
  34366. /**
  34367. * A callback function that defines what should happen when a device/context lost occurs.
  34368. *
  34369. * @type {Function}
  34370. */
  34371. this.onDeviceLost = this._onDeviceLost;
  34372. /**
  34373. * Whether the renderer has been initialized or not.
  34374. *
  34375. * @private
  34376. * @type {Boolean}
  34377. * @default false
  34378. */
  34379. this._initialized = false;
  34380. /**
  34381. * A reference to the promise which initializes the renderer.
  34382. *
  34383. * @private
  34384. * @type {Promise?}
  34385. * @default null
  34386. */
  34387. this._initPromise = null;
  34388. /**
  34389. * An array of compilation promises which are used in `compileAsync()`.
  34390. *
  34391. * @private
  34392. * @type {Array<Promise>?}
  34393. * @default null
  34394. */
  34395. this._compilationPromises = null;
  34396. /**
  34397. * Whether the renderer should render transparent render objects or not.
  34398. *
  34399. * @type {Boolean}
  34400. * @default true
  34401. */
  34402. this.transparent = true;
  34403. /**
  34404. * Whether the renderer should render opaque render objects or not.
  34405. *
  34406. * @type {Boolean}
  34407. * @default true
  34408. */
  34409. this.opaque = true;
  34410. /**
  34411. * Shadow map configuration
  34412. * @typedef {Object} ShadowMapConfig
  34413. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34414. * @property {Number} type - The shadow map type.
  34415. */
  34416. /**
  34417. * The renderer's shadow configuration.
  34418. *
  34419. * @type {module:Renderer~ShadowMapConfig}
  34420. */
  34421. this.shadowMap = {
  34422. enabled: false,
  34423. type: PCFShadowMap
  34424. };
  34425. /**
  34426. * XR configuration.
  34427. * @typedef {Object} XRConfig
  34428. * @property {Boolean} enabled - Whether to globally enable XR or not.
  34429. */
  34430. /**
  34431. * The renderer's XR manager.
  34432. *
  34433. * @type {XRManager}
  34434. */
  34435. this.xr = new XRManager( this );
  34436. /**
  34437. * Debug configuration.
  34438. * @typedef {Object} DebugConfig
  34439. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  34440. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  34441. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  34442. */
  34443. /**
  34444. * The renderer's debug configuration.
  34445. *
  34446. * @type {module:Renderer~DebugConfig}
  34447. */
  34448. this.debug = {
  34449. checkShaderErrors: true,
  34450. onShaderError: null,
  34451. getShaderAsync: async ( scene, camera, object ) => {
  34452. await this.compileAsync( scene, camera );
  34453. const renderList = this._renderLists.get( scene, camera );
  34454. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  34455. const material = scene.overrideMaterial || object.material;
  34456. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  34457. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  34458. return { fragmentShader, vertexShader };
  34459. }
  34460. };
  34461. }
  34462. /**
  34463. * Initializes the renderer so it is ready for usage.
  34464. *
  34465. * @async
  34466. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  34467. */
  34468. async init() {
  34469. if ( this._initialized ) {
  34470. throw new Error( 'Renderer: Backend has already been initialized.' );
  34471. }
  34472. if ( this._initPromise !== null ) {
  34473. return this._initPromise;
  34474. }
  34475. this._initPromise = new Promise( async ( resolve, reject ) => {
  34476. let backend = this.backend;
  34477. try {
  34478. await backend.init( this );
  34479. } catch ( error ) {
  34480. if ( this._getFallback !== null ) {
  34481. // try the fallback
  34482. try {
  34483. this.backend = backend = this._getFallback( error );
  34484. await backend.init( this );
  34485. } catch ( error ) {
  34486. reject( error );
  34487. return;
  34488. }
  34489. } else {
  34490. reject( error );
  34491. return;
  34492. }
  34493. }
  34494. this._nodes = new Nodes( this, backend );
  34495. this._animation = new Animation( this._nodes, this.info );
  34496. this._attributes = new Attributes( backend );
  34497. this._background = new Background( this, this._nodes );
  34498. this._geometries = new Geometries( this._attributes, this.info );
  34499. this._textures = new Textures( this, backend, this.info );
  34500. this._pipelines = new Pipelines( backend, this._nodes );
  34501. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  34502. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  34503. this._renderLists = new RenderLists( this.lighting );
  34504. this._bundles = new RenderBundles();
  34505. this._renderContexts = new RenderContexts();
  34506. //
  34507. this._animation.start();
  34508. this._initialized = true;
  34509. resolve();
  34510. } );
  34511. return this._initPromise;
  34512. }
  34513. /**
  34514. * The coordinate system of the renderer. The value of this property
  34515. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  34516. * `THREE.WebGPUCoordinateSystem`.
  34517. *
  34518. * @readonly
  34519. * @type {Number}
  34520. */
  34521. get coordinateSystem() {
  34522. return this.backend.coordinateSystem;
  34523. }
  34524. /**
  34525. * Compiles all materials in the given scene. This can be useful to avoid a
  34526. * phenomenon which is called "shader compilation stutter", which occurs when
  34527. * rendering an object with a new shader for the first time.
  34528. *
  34529. * If you want to add a 3D object to an existing scene, use the third optional
  34530. * parameter for applying the target scene. Note that the (target) scene's lighting
  34531. * and environment must be configured before calling this method.
  34532. *
  34533. * @async
  34534. * @param {Object3D} scene - The scene or 3D object to precompile.
  34535. * @param {Camera} camera - The camera that is used to render the scene.
  34536. * @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.
  34537. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  34538. */
  34539. async compileAsync( scene, camera, targetScene = null ) {
  34540. if ( this._isDeviceLost === true ) return;
  34541. if ( this._initialized === false ) await this.init();
  34542. // preserve render tree
  34543. const nodeFrame = this._nodes.nodeFrame;
  34544. const previousRenderId = nodeFrame.renderId;
  34545. const previousRenderContext = this._currentRenderContext;
  34546. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34547. const previousCompilationPromises = this._compilationPromises;
  34548. //
  34549. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34550. if ( targetScene === null ) targetScene = scene;
  34551. const renderTarget = this._renderTarget;
  34552. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  34553. const activeMipmapLevel = this._activeMipmapLevel;
  34554. const compilationPromises = [];
  34555. this._currentRenderContext = renderContext;
  34556. this._currentRenderObjectFunction = this.renderObject;
  34557. this._handleObjectFunction = this._createObjectPipeline;
  34558. this._compilationPromises = compilationPromises;
  34559. nodeFrame.renderId ++;
  34560. //
  34561. nodeFrame.update();
  34562. //
  34563. renderContext.depth = this.depth;
  34564. renderContext.stencil = this.stencil;
  34565. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34566. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34567. //
  34568. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34569. //
  34570. const renderList = this._renderLists.get( scene, camera );
  34571. renderList.begin();
  34572. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34573. // include lights from target scene
  34574. if ( targetScene !== scene ) {
  34575. targetScene.traverseVisible( function ( object ) {
  34576. if ( object.isLight && object.layers.test( camera.layers ) ) {
  34577. renderList.pushLight( object );
  34578. }
  34579. } );
  34580. }
  34581. renderList.finish();
  34582. //
  34583. if ( renderTarget !== null ) {
  34584. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34585. const renderTargetData = this._textures.get( renderTarget );
  34586. renderContext.textures = renderTargetData.textures;
  34587. renderContext.depthTexture = renderTargetData.depthTexture;
  34588. } else {
  34589. renderContext.textures = null;
  34590. renderContext.depthTexture = null;
  34591. }
  34592. //
  34593. this._background.update( sceneRef, renderList, renderContext );
  34594. // process render lists
  34595. const opaqueObjects = renderList.opaque;
  34596. const transparentObjects = renderList.transparent;
  34597. const transparentDoublePassObjects = renderList.transparentDoublePass;
  34598. const lightsNode = renderList.lightsNode;
  34599. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34600. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34601. // restore render tree
  34602. nodeFrame.renderId = previousRenderId;
  34603. this._currentRenderContext = previousRenderContext;
  34604. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34605. this._compilationPromises = previousCompilationPromises;
  34606. this._handleObjectFunction = this._renderObjectDirect;
  34607. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  34608. await Promise.all( compilationPromises );
  34609. }
  34610. /**
  34611. * Renders the scene in an async fashion.
  34612. *
  34613. * @async
  34614. * @param {Object3D} scene - The scene or 3D object to render.
  34615. * @param {Camera} camera - The camera.
  34616. * @return {Promise} A Promise that resolves when the render has been finished.
  34617. */
  34618. async renderAsync( scene, camera ) {
  34619. if ( this._initialized === false ) await this.init();
  34620. const renderContext = this._renderScene( scene, camera );
  34621. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  34622. }
  34623. /**
  34624. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  34625. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  34626. *
  34627. * @async
  34628. * @return {Promise} A Promise that resolves when synchronization has been finished.
  34629. */
  34630. async waitForGPU() {
  34631. await this.backend.waitForGPU();
  34632. }
  34633. /**
  34634. * Sets the given MRT configuration.
  34635. *
  34636. * @param {MRTNode} mrt - The MRT node to set.
  34637. * @return {Renderer} A reference to this renderer.
  34638. */
  34639. setMRT( mrt ) {
  34640. this._mrt = mrt;
  34641. return this;
  34642. }
  34643. /**
  34644. * Returns the MRT configuration.
  34645. *
  34646. * @return {MRTNode} The MRT configuration.
  34647. */
  34648. getMRT() {
  34649. return this._mrt;
  34650. }
  34651. /**
  34652. * Default implementation of the device lost callback.
  34653. *
  34654. * @private
  34655. * @param {Object} info - Information about the context lost.
  34656. */
  34657. _onDeviceLost( info ) {
  34658. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  34659. if ( info.reason ) {
  34660. errorMessage += `\nReason: ${info.reason}`;
  34661. }
  34662. console.error( errorMessage );
  34663. this._isDeviceLost = true;
  34664. }
  34665. /**
  34666. * Renders the given render bundle.
  34667. *
  34668. * @private
  34669. * @param {Object} bundle - Render bundle data.
  34670. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  34671. * @param {LightsNode} lightsNode - The current lights node.
  34672. */
  34673. _renderBundle( bundle, sceneRef, lightsNode ) {
  34674. const { bundleGroup, camera, renderList } = bundle;
  34675. const renderContext = this._currentRenderContext;
  34676. //
  34677. const renderBundle = this._bundles.get( bundleGroup, camera );
  34678. const renderBundleData = this.backend.get( renderBundle );
  34679. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  34680. //
  34681. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  34682. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  34683. renderBundleData.renderContexts.add( renderContext );
  34684. if ( renderBundleNeedsUpdate ) {
  34685. this.backend.beginBundle( renderContext );
  34686. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  34687. renderBundleData.renderObjects = [];
  34688. }
  34689. this._currentRenderBundle = renderBundle;
  34690. const opaqueObjects = renderList.opaque;
  34691. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34692. this._currentRenderBundle = null;
  34693. //
  34694. this.backend.finishBundle( renderContext, renderBundle );
  34695. renderBundleData.version = bundleGroup.version;
  34696. } else {
  34697. const { renderObjects } = renderBundleData;
  34698. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  34699. const renderObject = renderObjects[ i ];
  34700. if ( this._nodes.needsRefresh( renderObject ) ) {
  34701. this._nodes.updateBefore( renderObject );
  34702. this._nodes.updateForRender( renderObject );
  34703. this._bindings.updateForRender( renderObject );
  34704. this._nodes.updateAfter( renderObject );
  34705. }
  34706. }
  34707. }
  34708. this.backend.addBundle( renderContext, renderBundle );
  34709. }
  34710. /**
  34711. * Renders the scene or 3D object with the given camera. This method can only be called
  34712. * if the renderer has been initialized.
  34713. *
  34714. * The target of the method is the default framebuffer (meaning the canvas)
  34715. * or alternatively a render target when specified via `setRenderTarget()`.
  34716. *
  34717. * @param {Object3D} scene - The scene or 3D object to render.
  34718. * @param {Camera} camera - The camera to render the scene with.
  34719. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  34720. * Only returned when the renderer has not been initialized.
  34721. */
  34722. render( scene, camera ) {
  34723. if ( this._initialized === false ) {
  34724. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  34725. return this.renderAsync( scene, camera );
  34726. }
  34727. this._renderScene( scene, camera );
  34728. }
  34729. /**
  34730. * Returns an internal render target which is used when computing the output tone mapping
  34731. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  34732. * pass and not inline to achieve more correct results.
  34733. *
  34734. * @private
  34735. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  34736. */
  34737. _getFrameBufferTarget() {
  34738. const { currentToneMapping, currentColorSpace } = this;
  34739. const useToneMapping = currentToneMapping !== NoToneMapping;
  34740. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  34741. if ( useToneMapping === false && useColorSpace === false ) return null;
  34742. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  34743. const { depth, stencil } = this;
  34744. let frameBufferTarget = this._frameBufferTarget;
  34745. if ( frameBufferTarget === null ) {
  34746. frameBufferTarget = new RenderTarget( width, height, {
  34747. depthBuffer: depth,
  34748. stencilBuffer: stencil,
  34749. type: HalfFloatType, // FloatType
  34750. format: RGBAFormat,
  34751. colorSpace: LinearSRGBColorSpace,
  34752. generateMipmaps: false,
  34753. minFilter: LinearFilter,
  34754. magFilter: LinearFilter,
  34755. samples: this.samples
  34756. } );
  34757. frameBufferTarget.isPostProcessingRenderTarget = true;
  34758. this._frameBufferTarget = frameBufferTarget;
  34759. }
  34760. frameBufferTarget.depthBuffer = depth;
  34761. frameBufferTarget.stencilBuffer = stencil;
  34762. frameBufferTarget.setSize( width, height );
  34763. frameBufferTarget.viewport.copy( this._viewport );
  34764. frameBufferTarget.scissor.copy( this._scissor );
  34765. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  34766. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  34767. frameBufferTarget.scissorTest = this._scissorTest;
  34768. return frameBufferTarget;
  34769. }
  34770. /**
  34771. * Renders the scene or 3D object with the given camera.
  34772. *
  34773. * @private
  34774. * @param {Object3D} scene - The scene or 3D object to render.
  34775. * @param {Camera} camera - The camera to render the scene with.
  34776. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  34777. * @return {RenderContext} The current render context.
  34778. */
  34779. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  34780. if ( this._isDeviceLost === true ) return;
  34781. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  34782. // preserve render tree
  34783. const nodeFrame = this._nodes.nodeFrame;
  34784. const previousRenderId = nodeFrame.renderId;
  34785. const previousRenderContext = this._currentRenderContext;
  34786. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34787. //
  34788. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34789. const outputRenderTarget = this._renderTarget;
  34790. const activeCubeFace = this._activeCubeFace;
  34791. const activeMipmapLevel = this._activeMipmapLevel;
  34792. //
  34793. let renderTarget;
  34794. if ( frameBufferTarget !== null ) {
  34795. renderTarget = frameBufferTarget;
  34796. this.setRenderTarget( renderTarget );
  34797. } else {
  34798. renderTarget = outputRenderTarget;
  34799. }
  34800. //
  34801. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  34802. this._currentRenderContext = renderContext;
  34803. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  34804. //
  34805. this.info.calls ++;
  34806. this.info.render.calls ++;
  34807. this.info.render.frameCalls ++;
  34808. nodeFrame.renderId = this.info.calls;
  34809. //
  34810. const coordinateSystem = this.coordinateSystem;
  34811. const xr = this.xr;
  34812. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  34813. camera.coordinateSystem = coordinateSystem;
  34814. camera.updateProjectionMatrix();
  34815. if ( camera.isArrayCamera ) {
  34816. for ( const subCamera of camera.cameras ) {
  34817. subCamera.coordinateSystem = coordinateSystem;
  34818. subCamera.updateProjectionMatrix();
  34819. }
  34820. }
  34821. }
  34822. //
  34823. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  34824. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  34825. if ( xr.enabled === true && xr.isPresenting === true ) {
  34826. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  34827. camera = xr.getCamera(); // use XR camera for rendering
  34828. }
  34829. //
  34830. let viewport = this._viewport;
  34831. let scissor = this._scissor;
  34832. let pixelRatio = this._pixelRatio;
  34833. if ( renderTarget !== null ) {
  34834. viewport = renderTarget.viewport;
  34835. scissor = renderTarget.scissor;
  34836. pixelRatio = 1;
  34837. }
  34838. this.getDrawingBufferSize( _drawingBufferSize );
  34839. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  34840. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  34841. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  34842. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  34843. renderContext.viewportValue.width >>= activeMipmapLevel;
  34844. renderContext.viewportValue.height >>= activeMipmapLevel;
  34845. renderContext.viewportValue.minDepth = minDepth;
  34846. renderContext.viewportValue.maxDepth = maxDepth;
  34847. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  34848. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  34849. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  34850. renderContext.scissorValue.width >>= activeMipmapLevel;
  34851. renderContext.scissorValue.height >>= activeMipmapLevel;
  34852. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34853. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34854. //
  34855. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34856. //
  34857. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  34858. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  34859. const renderList = this._renderLists.get( scene, camera );
  34860. renderList.begin();
  34861. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34862. renderList.finish();
  34863. if ( this.sortObjects === true ) {
  34864. renderList.sort( this._opaqueSort, this._transparentSort );
  34865. }
  34866. //
  34867. if ( renderTarget !== null ) {
  34868. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34869. const renderTargetData = this._textures.get( renderTarget );
  34870. renderContext.textures = renderTargetData.textures;
  34871. renderContext.depthTexture = renderTargetData.depthTexture;
  34872. renderContext.width = renderTargetData.width;
  34873. renderContext.height = renderTargetData.height;
  34874. renderContext.renderTarget = renderTarget;
  34875. renderContext.depth = renderTarget.depthBuffer;
  34876. renderContext.stencil = renderTarget.stencilBuffer;
  34877. } else {
  34878. renderContext.textures = null;
  34879. renderContext.depthTexture = null;
  34880. renderContext.width = this.domElement.width;
  34881. renderContext.height = this.domElement.height;
  34882. renderContext.depth = this.depth;
  34883. renderContext.stencil = this.stencil;
  34884. }
  34885. renderContext.width >>= activeMipmapLevel;
  34886. renderContext.height >>= activeMipmapLevel;
  34887. renderContext.activeCubeFace = activeCubeFace;
  34888. renderContext.activeMipmapLevel = activeMipmapLevel;
  34889. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  34890. //
  34891. this._background.update( sceneRef, renderList, renderContext );
  34892. //
  34893. this.backend.beginRender( renderContext );
  34894. // process render lists
  34895. const {
  34896. bundles,
  34897. lightsNode,
  34898. transparentDoublePass: transparentDoublePassObjects,
  34899. transparent: transparentObjects,
  34900. opaque: opaqueObjects
  34901. } = renderList;
  34902. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  34903. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34904. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34905. // finish render pass
  34906. this.backend.finishRender( renderContext );
  34907. // restore render tree
  34908. nodeFrame.renderId = previousRenderId;
  34909. this._currentRenderContext = previousRenderContext;
  34910. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34911. //
  34912. if ( frameBufferTarget !== null ) {
  34913. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  34914. const quad = this._quad;
  34915. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  34916. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  34917. quad.material.needsUpdate = true;
  34918. }
  34919. this._renderScene( quad, quad.camera, false );
  34920. }
  34921. //
  34922. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  34923. //
  34924. return renderContext;
  34925. }
  34926. /**
  34927. * Returns the maximum available anisotropy for texture filtering.
  34928. *
  34929. * @return {Number} The maximum available anisotropy.
  34930. */
  34931. getMaxAnisotropy() {
  34932. return this.backend.getMaxAnisotropy();
  34933. }
  34934. /**
  34935. * Returns the active cube face.
  34936. *
  34937. * @return {Number} The active cube face.
  34938. */
  34939. getActiveCubeFace() {
  34940. return this._activeCubeFace;
  34941. }
  34942. /**
  34943. * Returns the active mipmap level.
  34944. *
  34945. * @return {Number} The active mipmap level.
  34946. */
  34947. getActiveMipmapLevel() {
  34948. return this._activeMipmapLevel;
  34949. }
  34950. /**
  34951. * Applications are advised to always define the animation loop
  34952. * with this method and not manually with `requestAnimationFrame()`
  34953. * for best compatibility.
  34954. *
  34955. * @async
  34956. * @param {Function} callback - The application's animation loop.
  34957. * @return {Promise} A Promise that resolves when the set has been executed.
  34958. */
  34959. async setAnimationLoop( callback ) {
  34960. if ( this._initialized === false ) await this.init();
  34961. this._animation.setAnimationLoop( callback );
  34962. }
  34963. /**
  34964. * Can be used to transfer buffer data from a storage buffer attribute
  34965. * from the GPU to the CPU in context of compute shaders.
  34966. *
  34967. * @async
  34968. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  34969. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  34970. */
  34971. async getArrayBufferAsync( attribute ) {
  34972. return await this.backend.getArrayBufferAsync( attribute );
  34973. }
  34974. /**
  34975. * Returns the rendering context.
  34976. *
  34977. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  34978. */
  34979. getContext() {
  34980. return this.backend.getContext();
  34981. }
  34982. /**
  34983. * Returns the pixel ratio.
  34984. *
  34985. * @return {Number} The pixel ratio.
  34986. */
  34987. getPixelRatio() {
  34988. return this._pixelRatio;
  34989. }
  34990. /**
  34991. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  34992. *
  34993. * @param {Vector2} target - The method writes the result in this target object.
  34994. * @return {Vector2} The drawing buffer size.
  34995. */
  34996. getDrawingBufferSize( target ) {
  34997. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  34998. }
  34999. /**
  35000. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35001. *
  35002. * @param {Vector2} target - The method writes the result in this target object.
  35003. * @return {Vector2} The drawing buffer size.
  35004. */
  35005. getSize( target ) {
  35006. return target.set( this._width, this._height );
  35007. }
  35008. /**
  35009. * Sets the given pixel ration and resizes the canvas if necessary.
  35010. *
  35011. * @param {Number} [value=1] - The pixel ratio.
  35012. */
  35013. setPixelRatio( value = 1 ) {
  35014. if ( this._pixelRatio === value ) return;
  35015. this._pixelRatio = value;
  35016. this.setSize( this._width, this._height, false );
  35017. }
  35018. /**
  35019. * This method allows to define the drawing buffer size by specifying
  35020. * width, height and pixel ratio all at once. The size of the drawing
  35021. * buffer is computed with this formula:
  35022. * ````
  35023. * size.x = width * pixelRatio;
  35024. * size.y = height * pixelRatio;
  35025. *```
  35026. *
  35027. * @param {Number} width - The width in logical pixels.
  35028. * @param {Number} height - The height in logical pixels.
  35029. * @param {Number} pixelRatio - The pixel ratio.
  35030. */
  35031. setDrawingBufferSize( width, height, pixelRatio ) {
  35032. this._width = width;
  35033. this._height = height;
  35034. this._pixelRatio = pixelRatio;
  35035. this.domElement.width = Math.floor( width * pixelRatio );
  35036. this.domElement.height = Math.floor( height * pixelRatio );
  35037. this.setViewport( 0, 0, width, height );
  35038. if ( this._initialized ) this.backend.updateSize();
  35039. }
  35040. /**
  35041. * Sets the size of the renderer.
  35042. *
  35043. * @param {Number} width - The width in logical pixels.
  35044. * @param {Number} height - The height in logical pixels.
  35045. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  35046. */
  35047. setSize( width, height, updateStyle = true ) {
  35048. this._width = width;
  35049. this._height = height;
  35050. this.domElement.width = Math.floor( width * this._pixelRatio );
  35051. this.domElement.height = Math.floor( height * this._pixelRatio );
  35052. if ( updateStyle === true ) {
  35053. this.domElement.style.width = width + 'px';
  35054. this.domElement.style.height = height + 'px';
  35055. }
  35056. this.setViewport( 0, 0, width, height );
  35057. if ( this._initialized ) this.backend.updateSize();
  35058. }
  35059. /**
  35060. * Defines a manual sort function for the opaque render list.
  35061. * Pass `null` to use the default sort.
  35062. *
  35063. * @param {Function} method - The sort function.
  35064. */
  35065. setOpaqueSort( method ) {
  35066. this._opaqueSort = method;
  35067. }
  35068. /**
  35069. * Defines a manual sort function for the transparent render list.
  35070. * Pass `null` to use the default sort.
  35071. *
  35072. * @param {Function} method - The sort function.
  35073. */
  35074. setTransparentSort( method ) {
  35075. this._transparentSort = method;
  35076. }
  35077. /**
  35078. * Returns the scissor rectangle.
  35079. *
  35080. * @param {Vector4} target - The method writes the result in this target object.
  35081. * @return {Vector4} The scissor rectangle.
  35082. */
  35083. getScissor( target ) {
  35084. const scissor = this._scissor;
  35085. target.x = scissor.x;
  35086. target.y = scissor.y;
  35087. target.width = scissor.width;
  35088. target.height = scissor.height;
  35089. return target;
  35090. }
  35091. /**
  35092. * Defines the scissor rectangle.
  35093. *
  35094. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  35095. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  35096. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  35097. * @param {Number} width - The width of the scissor box in logical pixel unit.
  35098. * @param {Number} height - The height of the scissor box in logical pixel unit.
  35099. */
  35100. setScissor( x, y, width, height ) {
  35101. const scissor = this._scissor;
  35102. if ( x.isVector4 ) {
  35103. scissor.copy( x );
  35104. } else {
  35105. scissor.set( x, y, width, height );
  35106. }
  35107. }
  35108. /**
  35109. * Returns the scissor test value.
  35110. *
  35111. * @return {Boolean} Whether the scissor test should be enabled or not.
  35112. */
  35113. getScissorTest() {
  35114. return this._scissorTest;
  35115. }
  35116. /**
  35117. * Defines the scissor test.
  35118. *
  35119. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35120. */
  35121. setScissorTest( boolean ) {
  35122. this._scissorTest = boolean;
  35123. this.backend.setScissorTest( boolean );
  35124. }
  35125. /**
  35126. * Returns the viewport definition.
  35127. *
  35128. * @param {Vector4} target - The method writes the result in this target object.
  35129. * @return {Vector4} The viewport definition.
  35130. */
  35131. getViewport( target ) {
  35132. return target.copy( this._viewport );
  35133. }
  35134. /**
  35135. * Defines the viewport.
  35136. *
  35137. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35138. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35139. * @param {Number} width - The width of the viewport in logical pixel unit.
  35140. * @param {Number} height - The height of the viewport in logical pixel unit.
  35141. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35142. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35143. */
  35144. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35145. const viewport = this._viewport;
  35146. if ( x.isVector4 ) {
  35147. viewport.copy( x );
  35148. } else {
  35149. viewport.set( x, y, width, height );
  35150. }
  35151. viewport.minDepth = minDepth;
  35152. viewport.maxDepth = maxDepth;
  35153. }
  35154. /**
  35155. * Returns the clear color.
  35156. *
  35157. * @param {Color} target - The method writes the result in this target object.
  35158. * @return {Color} The clear color.
  35159. */
  35160. getClearColor( target ) {
  35161. return target.copy( this._clearColor );
  35162. }
  35163. /**
  35164. * Defines the clear color and optionally the clear alpha.
  35165. *
  35166. * @param {Color} color - The clear color.
  35167. * @param {Number} [alpha=1] - The clear alpha.
  35168. */
  35169. setClearColor( color, alpha = 1 ) {
  35170. this._clearColor.set( color );
  35171. this._clearColor.a = alpha;
  35172. }
  35173. /**
  35174. * Returns the clear alpha.
  35175. *
  35176. * @return {Number} The clear alpha.
  35177. */
  35178. getClearAlpha() {
  35179. return this._clearColor.a;
  35180. }
  35181. /**
  35182. * Defines the clear alpha.
  35183. *
  35184. * @param {Number} alpha - The clear alpha.
  35185. */
  35186. setClearAlpha( alpha ) {
  35187. this._clearColor.a = alpha;
  35188. }
  35189. /**
  35190. * Returns the clear depth.
  35191. *
  35192. * @return {Number} The clear depth.
  35193. */
  35194. getClearDepth() {
  35195. return this._clearDepth;
  35196. }
  35197. /**
  35198. * Defines the clear depth.
  35199. *
  35200. * @param {Number} depth - The clear depth.
  35201. */
  35202. setClearDepth( depth ) {
  35203. this._clearDepth = depth;
  35204. }
  35205. /**
  35206. * Returns the clear stencil.
  35207. *
  35208. * @return {Number} The clear stencil.
  35209. */
  35210. getClearStencil() {
  35211. return this._clearStencil;
  35212. }
  35213. /**
  35214. * Defines the clear stencil.
  35215. *
  35216. * @param {Number} stencil - The clear stencil.
  35217. */
  35218. setClearStencil( stencil ) {
  35219. this._clearStencil = stencil;
  35220. }
  35221. /**
  35222. * This method performs an occlusion query for the given 3D object.
  35223. * It returns `true` if the given 3D object is fully occluded by other
  35224. * 3D objects in the scene.
  35225. *
  35226. * @param {Object3D} object - The 3D object to test.
  35227. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35228. */
  35229. isOccluded( object ) {
  35230. const renderContext = this._currentRenderContext;
  35231. return renderContext && this.backend.isOccluded( renderContext, object );
  35232. }
  35233. /**
  35234. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35235. *
  35236. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35237. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35238. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35239. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35240. * Only returned when the renderer has not been initialized.
  35241. */
  35242. clear( color = true, depth = true, stencil = true ) {
  35243. if ( this._initialized === false ) {
  35244. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35245. return this.clearAsync( color, depth, stencil );
  35246. }
  35247. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35248. let renderContext = null;
  35249. if ( renderTarget !== null ) {
  35250. this._textures.updateRenderTarget( renderTarget );
  35251. const renderTargetData = this._textures.get( renderTarget );
  35252. renderContext = this._renderContexts.getForClear( renderTarget );
  35253. renderContext.textures = renderTargetData.textures;
  35254. renderContext.depthTexture = renderTargetData.depthTexture;
  35255. renderContext.width = renderTargetData.width;
  35256. renderContext.height = renderTargetData.height;
  35257. renderContext.renderTarget = renderTarget;
  35258. renderContext.depth = renderTarget.depthBuffer;
  35259. renderContext.stencil = renderTarget.stencilBuffer;
  35260. }
  35261. // #30329
  35262. renderContext.clearColorValue = this._clearColor;
  35263. this.backend.clear( color, depth, stencil, renderContext );
  35264. if ( renderTarget !== null && this._renderTarget === null ) {
  35265. // If a color space transform or tone mapping is required,
  35266. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35267. const quad = this._quad;
  35268. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35269. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35270. quad.material.needsUpdate = true;
  35271. }
  35272. this._renderScene( quad, quad.camera, false );
  35273. }
  35274. }
  35275. /**
  35276. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35277. *
  35278. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35279. * Only returned when the renderer has not been initialized.
  35280. */
  35281. clearColor() {
  35282. return this.clear( true, false, false );
  35283. }
  35284. /**
  35285. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35286. *
  35287. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35288. * Only returned when the renderer has not been initialized.
  35289. */
  35290. clearDepth() {
  35291. return this.clear( false, true, false );
  35292. }
  35293. /**
  35294. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35295. *
  35296. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35297. * Only returned when the renderer has not been initialized.
  35298. */
  35299. clearStencil() {
  35300. return this.clear( false, false, true );
  35301. }
  35302. /**
  35303. * Async version of {@link module:Renderer~Renderer#clear}.
  35304. *
  35305. * @async
  35306. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35307. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35308. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35309. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35310. */
  35311. async clearAsync( color = true, depth = true, stencil = true ) {
  35312. if ( this._initialized === false ) await this.init();
  35313. this.clear( color, depth, stencil );
  35314. }
  35315. /**
  35316. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35317. *
  35318. * @async
  35319. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35320. */
  35321. async clearColorAsync() {
  35322. this.clearAsync( true, false, false );
  35323. }
  35324. /**
  35325. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35326. *
  35327. * @async
  35328. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35329. */
  35330. async clearDepthAsync() {
  35331. this.clearAsync( false, true, false );
  35332. }
  35333. /**
  35334. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35335. *
  35336. * @async
  35337. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35338. */
  35339. async clearStencilAsync() {
  35340. this.clearAsync( false, false, true );
  35341. }
  35342. /**
  35343. * The current output tone mapping of the renderer. When a render target is set,
  35344. * the output tone mapping is always `NoToneMapping`.
  35345. *
  35346. * @type {Number}
  35347. */
  35348. get currentToneMapping() {
  35349. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35350. }
  35351. /**
  35352. * The current output color space of the renderer. When a render target is set,
  35353. * the output color space is always `LinearSRGBColorSpace`.
  35354. *
  35355. * @type {String}
  35356. */
  35357. get currentColorSpace() {
  35358. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35359. }
  35360. /**
  35361. * Frees all internal resources of the renderer. Call this method if the renderer
  35362. * is no longer in use by your app.
  35363. */
  35364. dispose() {
  35365. this.info.dispose();
  35366. this.backend.dispose();
  35367. this._animation.dispose();
  35368. this._objects.dispose();
  35369. this._pipelines.dispose();
  35370. this._nodes.dispose();
  35371. this._bindings.dispose();
  35372. this._renderLists.dispose();
  35373. this._renderContexts.dispose();
  35374. this._textures.dispose();
  35375. this.setRenderTarget( null );
  35376. this.setAnimationLoop( null );
  35377. }
  35378. /**
  35379. * Sets the given render target. Calling this method means the renderer does not
  35380. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35381. * Use `null` as the first argument to reset the state.
  35382. *
  35383. * @param {RenderTarget?} renderTarget - The render target to set.
  35384. * @param {Number} [activeCubeFace=0] - The active cube face.
  35385. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35386. */
  35387. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35388. this._renderTarget = renderTarget;
  35389. this._activeCubeFace = activeCubeFace;
  35390. this._activeMipmapLevel = activeMipmapLevel;
  35391. }
  35392. /**
  35393. * Returns the current render target.
  35394. *
  35395. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35396. */
  35397. getRenderTarget() {
  35398. return this._renderTarget;
  35399. }
  35400. /**
  35401. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35402. *
  35403. * @callback renderObjectFunction
  35404. * @param {Object3D} object - The 3D object.
  35405. * @param {Scene} scene - The scene the 3D object belongs to.
  35406. * @param {Camera} camera - The camera the object should be rendered with.
  35407. * @param {BufferGeometry} geometry - The object's geometry.
  35408. * @param {Material} material - The object's material.
  35409. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35410. * @param {LightsNode} lightsNode - The current lights node.
  35411. * @param {ClippingContext} clippingContext - The clipping context.
  35412. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35413. */
  35414. /**
  35415. * Sets the given render object function. Calling this method overwrites the default implementation
  35416. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  35417. * if you want to modify the way objects are rendered. For example you can define things like "every
  35418. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  35419. * The custom function must always call `renderObject()` in its implementation.
  35420. *
  35421. * Use `null` as the first argument to reset the state.
  35422. *
  35423. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  35424. */
  35425. setRenderObjectFunction( renderObjectFunction ) {
  35426. this._renderObjectFunction = renderObjectFunction;
  35427. }
  35428. /**
  35429. * Returns the current render object function.
  35430. *
  35431. * @return {Function?} The current render object function. Returns `null` if no function is set.
  35432. */
  35433. getRenderObjectFunction() {
  35434. return this._renderObjectFunction;
  35435. }
  35436. /**
  35437. * Execute a single or an array of compute nodes. This method can only be called
  35438. * if the renderer has been initialized.
  35439. *
  35440. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35441. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  35442. */
  35443. compute( computeNodes ) {
  35444. if ( this._isDeviceLost === true ) return;
  35445. if ( this._initialized === false ) {
  35446. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  35447. return this.computeAsync( computeNodes );
  35448. }
  35449. //
  35450. const nodeFrame = this._nodes.nodeFrame;
  35451. const previousRenderId = nodeFrame.renderId;
  35452. //
  35453. this.info.calls ++;
  35454. this.info.compute.calls ++;
  35455. this.info.compute.frameCalls ++;
  35456. nodeFrame.renderId = this.info.calls;
  35457. //
  35458. const backend = this.backend;
  35459. const pipelines = this._pipelines;
  35460. const bindings = this._bindings;
  35461. const nodes = this._nodes;
  35462. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  35463. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  35464. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  35465. }
  35466. backend.beginCompute( computeNodes );
  35467. for ( const computeNode of computeList ) {
  35468. // onInit
  35469. if ( pipelines.has( computeNode ) === false ) {
  35470. const dispose = () => {
  35471. computeNode.removeEventListener( 'dispose', dispose );
  35472. pipelines.delete( computeNode );
  35473. bindings.delete( computeNode );
  35474. nodes.delete( computeNode );
  35475. };
  35476. computeNode.addEventListener( 'dispose', dispose );
  35477. //
  35478. const onInitFn = computeNode.onInitFunction;
  35479. if ( onInitFn !== null ) {
  35480. onInitFn.call( computeNode, { renderer: this } );
  35481. }
  35482. }
  35483. nodes.updateForCompute( computeNode );
  35484. bindings.updateForCompute( computeNode );
  35485. const computeBindings = bindings.getForCompute( computeNode );
  35486. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  35487. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  35488. }
  35489. backend.finishCompute( computeNodes );
  35490. //
  35491. nodeFrame.renderId = previousRenderId;
  35492. }
  35493. /**
  35494. * Execute a single or an array of compute nodes.
  35495. *
  35496. * @async
  35497. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35498. * @return {Promise} A Promise that resolve when the compute has finished.
  35499. */
  35500. async computeAsync( computeNodes ) {
  35501. if ( this._initialized === false ) await this.init();
  35502. this.compute( computeNodes );
  35503. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  35504. }
  35505. /**
  35506. * Checks if the given feature is supported by the selected backend.
  35507. *
  35508. * @async
  35509. * @param {String} name - The feature's name.
  35510. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  35511. */
  35512. async hasFeatureAsync( name ) {
  35513. if ( this._initialized === false ) await this.init();
  35514. return this.backend.hasFeature( name );
  35515. }
  35516. /**
  35517. * Checks if the given feature is supported by the selected backend. If the
  35518. * renderer has not been initialized, this method always returns `false`.
  35519. *
  35520. * @param {String} name - The feature's name.
  35521. * @return {Boolean} Whether the feature is supported or not.
  35522. */
  35523. hasFeature( name ) {
  35524. if ( this._initialized === false ) {
  35525. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  35526. return false;
  35527. }
  35528. return this.backend.hasFeature( name );
  35529. }
  35530. /**
  35531. * Returns `true` when the renderer has been initialized.
  35532. *
  35533. * @return {Boolean} Whether the renderer has been initialized or not.
  35534. */
  35535. hasInitialized() {
  35536. return this._initialized;
  35537. }
  35538. /**
  35539. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35540. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35541. *
  35542. * @async
  35543. * @param {Texture} texture - The texture.
  35544. * @return {Promise} A Promise that resolves when the texture has been initialized.
  35545. */
  35546. async initTextureAsync( texture ) {
  35547. if ( this._initialized === false ) await this.init();
  35548. this._textures.updateTexture( texture );
  35549. }
  35550. /**
  35551. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35552. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35553. *
  35554. * This method can only be used if the renderer has been initialized.
  35555. *
  35556. * @param {Texture} texture - The texture.
  35557. */
  35558. initTexture( texture ) {
  35559. if ( this._initialized === false ) {
  35560. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  35561. }
  35562. this._textures.updateTexture( texture );
  35563. }
  35564. /**
  35565. * Copies the current bound framebuffer into the given texture.
  35566. *
  35567. * @param {FramebufferTexture} framebufferTexture - The texture.
  35568. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  35569. */
  35570. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  35571. if ( rectangle !== null ) {
  35572. if ( rectangle.isVector2 ) {
  35573. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  35574. } else if ( rectangle.isVector4 ) {
  35575. rectangle = _vector4.copy( rectangle ).floor();
  35576. } else {
  35577. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  35578. return;
  35579. }
  35580. } else {
  35581. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  35582. }
  35583. //
  35584. let renderContext = this._currentRenderContext;
  35585. let renderTarget;
  35586. if ( renderContext !== null ) {
  35587. renderTarget = renderContext.renderTarget;
  35588. } else {
  35589. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35590. if ( renderTarget !== null ) {
  35591. this._textures.updateRenderTarget( renderTarget );
  35592. renderContext = this._textures.get( renderTarget );
  35593. }
  35594. }
  35595. //
  35596. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  35597. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  35598. }
  35599. /**
  35600. * Copies data of source texture into a destination texture.
  35601. *
  35602. * @param {Texture} srcTexture - The source texture.
  35603. * @param {Texture} dstTexture - The destination texture.
  35604. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  35605. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  35606. * @param {Number} level - The mipmap level to copy.
  35607. */
  35608. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  35609. this._textures.updateTexture( srcTexture );
  35610. this._textures.updateTexture( dstTexture );
  35611. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  35612. }
  35613. /**
  35614. * Reads pixel data from the given render target.
  35615. *
  35616. * @async
  35617. * @param {RenderTarget} renderTarget - The render target to read from.
  35618. * @param {Number} x - The `x` coordinate of the copy region's origin.
  35619. * @param {Number} y - The `y` coordinate of the copy region's origin.
  35620. * @param {Number} width - The width of the copy region.
  35621. * @param {Number} height - The height of the copy region.
  35622. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  35623. * @param {Number} [faceIndex=0] - The active cube face index.
  35624. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  35625. */
  35626. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  35627. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  35628. }
  35629. /**
  35630. * Analyzes the given 3D object's hierarchy and builds render lists from the
  35631. * processed hierarchy.
  35632. *
  35633. * @param {Object3D} object - The 3D object to process (usually a scene).
  35634. * @param {Camera} camera - The camera the object is rendered with.
  35635. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  35636. * @param {RenderList} renderList - The current render list.
  35637. * @param {ClippingContext} clippingContext - The current clipping context.
  35638. */
  35639. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  35640. if ( object.visible === false ) return;
  35641. const visible = object.layers.test( camera.layers );
  35642. if ( visible ) {
  35643. if ( object.isGroup ) {
  35644. groupOrder = object.renderOrder;
  35645. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  35646. } else if ( object.isLOD ) {
  35647. if ( object.autoUpdate === true ) object.update( camera );
  35648. } else if ( object.isLight ) {
  35649. renderList.pushLight( object );
  35650. } else if ( object.isSprite ) {
  35651. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  35652. if ( this.sortObjects === true ) {
  35653. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  35654. }
  35655. const { geometry, material } = object;
  35656. if ( material.visible ) {
  35657. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35658. }
  35659. }
  35660. } else if ( object.isLineLoop ) {
  35661. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  35662. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  35663. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  35664. const { geometry, material } = object;
  35665. if ( this.sortObjects === true ) {
  35666. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  35667. _vector4
  35668. .copy( geometry.boundingSphere.center )
  35669. .applyMatrix4( object.matrixWorld )
  35670. .applyMatrix4( _projScreenMatrix );
  35671. }
  35672. if ( Array.isArray( material ) ) {
  35673. const groups = geometry.groups;
  35674. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  35675. const group = groups[ i ];
  35676. const groupMaterial = material[ group.materialIndex ];
  35677. if ( groupMaterial && groupMaterial.visible ) {
  35678. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  35679. }
  35680. }
  35681. } else if ( material.visible ) {
  35682. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35683. }
  35684. }
  35685. }
  35686. }
  35687. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  35688. const baseRenderList = renderList;
  35689. // replace render list
  35690. renderList = this._renderLists.get( object, camera );
  35691. renderList.begin();
  35692. baseRenderList.pushBundle( {
  35693. bundleGroup: object,
  35694. camera,
  35695. renderList,
  35696. } );
  35697. renderList.finish();
  35698. }
  35699. const children = object.children;
  35700. for ( let i = 0, l = children.length; i < l; i ++ ) {
  35701. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  35702. }
  35703. }
  35704. /**
  35705. * Renders the given render bundles.
  35706. *
  35707. * @private
  35708. * @param {Array<Object>} bundles - Array with render bundle data.
  35709. * @param {Scene} sceneRef - The scene the render bundles belong to.
  35710. * @param {LightsNode} lightsNode - The current lights node.
  35711. */
  35712. _renderBundles( bundles, sceneRef, lightsNode ) {
  35713. for ( const bundle of bundles ) {
  35714. this._renderBundle( bundle, sceneRef, lightsNode );
  35715. }
  35716. }
  35717. /**
  35718. * Renders the transparent objects from the given render lists.
  35719. *
  35720. * @private
  35721. * @param {Array<Object>} renderList - The transparent render list.
  35722. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  35723. * @param {Camera} camera - The camera the render list should be rendered with.
  35724. * @param {Scene} scene - The scene the render list belongs to.
  35725. * @param {LightsNode} lightsNode - The current lights node.
  35726. */
  35727. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  35728. if ( doublePassList.length > 0 ) {
  35729. // render back side
  35730. for ( const { material } of doublePassList ) {
  35731. material.side = BackSide;
  35732. }
  35733. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  35734. // render front side
  35735. for ( const { material } of doublePassList ) {
  35736. material.side = FrontSide;
  35737. }
  35738. this._renderObjects( renderList, camera, scene, lightsNode );
  35739. // restore
  35740. for ( const { material } of doublePassList ) {
  35741. material.side = DoubleSide;
  35742. }
  35743. } else {
  35744. this._renderObjects( renderList, camera, scene, lightsNode );
  35745. }
  35746. }
  35747. /**
  35748. * Renders the objects from the given render list.
  35749. *
  35750. * @private
  35751. * @param {Array<Object>} renderList - The render list.
  35752. * @param {Camera} camera - The camera the render list should be rendered with.
  35753. * @param {Scene} scene - The scene the render list belongs to.
  35754. * @param {LightsNode} lightsNode - The current lights node.
  35755. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35756. */
  35757. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  35758. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  35759. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  35760. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  35761. }
  35762. }
  35763. /**
  35764. * This method represents the default render object function that manages the render lifecycle
  35765. * of the object.
  35766. *
  35767. * @param {Object3D} object - The 3D object.
  35768. * @param {Scene} scene - The scene the 3D object belongs to.
  35769. * @param {Camera} camera - The camera the object should be rendered with.
  35770. * @param {BufferGeometry} geometry - The object's geometry.
  35771. * @param {Material} material - The object's material.
  35772. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35773. * @param {LightsNode} lightsNode - The current lights node.
  35774. * @param {ClippingContext} clippingContext - The clipping context.
  35775. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35776. */
  35777. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  35778. let overridePositionNode;
  35779. let overrideColorNode;
  35780. let overrideDepthNode;
  35781. //
  35782. object.onBeforeRender( this, scene, camera, geometry, material, group );
  35783. //
  35784. if ( scene.overrideMaterial !== null ) {
  35785. const overrideMaterial = scene.overrideMaterial;
  35786. if ( material.positionNode && material.positionNode.isNode ) {
  35787. overridePositionNode = overrideMaterial.positionNode;
  35788. overrideMaterial.positionNode = material.positionNode;
  35789. }
  35790. overrideMaterial.alphaTest = material.alphaTest;
  35791. overrideMaterial.alphaMap = material.alphaMap;
  35792. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  35793. if ( overrideMaterial.isShadowPassMaterial ) {
  35794. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  35795. if ( material.depthNode && material.depthNode.isNode ) {
  35796. overrideDepthNode = overrideMaterial.depthNode;
  35797. overrideMaterial.depthNode = material.depthNode;
  35798. }
  35799. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  35800. overrideColorNode = overrideMaterial.colorNode;
  35801. overrideMaterial.colorNode = material.castShadowNode;
  35802. }
  35803. }
  35804. material = overrideMaterial;
  35805. }
  35806. //
  35807. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  35808. material.side = BackSide;
  35809. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  35810. material.side = FrontSide;
  35811. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  35812. material.side = DoubleSide;
  35813. } else {
  35814. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  35815. }
  35816. //
  35817. if ( overridePositionNode !== undefined ) {
  35818. scene.overrideMaterial.positionNode = overridePositionNode;
  35819. }
  35820. if ( overrideDepthNode !== undefined ) {
  35821. scene.overrideMaterial.depthNode = overrideDepthNode;
  35822. }
  35823. if ( overrideColorNode !== undefined ) {
  35824. scene.overrideMaterial.colorNode = overrideColorNode;
  35825. }
  35826. //
  35827. object.onAfterRender( this, scene, camera, geometry, material, group );
  35828. }
  35829. /**
  35830. * This method represents the default `_handleObjectFunction` implementation which creates
  35831. * a render object from the given data and performs the draw command with the selected backend.
  35832. *
  35833. * @private
  35834. * @param {Object3D} object - The 3D object.
  35835. * @param {Material} material - The object's material.
  35836. * @param {Scene} scene - The scene the 3D object belongs to.
  35837. * @param {Camera} camera - The camera the object should be rendered with.
  35838. * @param {LightsNode} lightsNode - The current lights node.
  35839. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35840. * @param {ClippingContext} clippingContext - The clipping context.
  35841. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35842. */
  35843. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35844. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35845. renderObject.drawRange = object.geometry.drawRange;
  35846. renderObject.group = group;
  35847. //
  35848. const needsRefresh = this._nodes.needsRefresh( renderObject );
  35849. if ( needsRefresh ) {
  35850. this._nodes.updateBefore( renderObject );
  35851. this._geometries.updateForRender( renderObject );
  35852. this._nodes.updateForRender( renderObject );
  35853. this._bindings.updateForRender( renderObject );
  35854. }
  35855. this._pipelines.updateForRender( renderObject );
  35856. //
  35857. if ( this._currentRenderBundle !== null ) {
  35858. const renderBundleData = this.backend.get( this._currentRenderBundle );
  35859. renderBundleData.renderObjects.push( renderObject );
  35860. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  35861. }
  35862. this.backend.draw( renderObject, this.info );
  35863. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  35864. }
  35865. /**
  35866. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  35867. * Used in `compileAsync()`.
  35868. *
  35869. * @private
  35870. * @param {Object3D} object - The 3D object.
  35871. * @param {Material} material - The object's material.
  35872. * @param {Scene} scene - The scene the 3D object belongs to.
  35873. * @param {Camera} camera - The camera the object should be rendered with.
  35874. * @param {LightsNode} lightsNode - The current lights node.
  35875. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35876. * @param {ClippingContext} clippingContext - The clipping context.
  35877. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35878. */
  35879. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35880. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35881. renderObject.drawRange = object.geometry.drawRange;
  35882. renderObject.group = group;
  35883. //
  35884. this._nodes.updateBefore( renderObject );
  35885. this._geometries.updateForRender( renderObject );
  35886. this._nodes.updateForRender( renderObject );
  35887. this._bindings.updateForRender( renderObject );
  35888. this._pipelines.getForRender( renderObject, this._compilationPromises );
  35889. this._nodes.updateAfter( renderObject );
  35890. }
  35891. /**
  35892. * Alias for `compileAsync()`.
  35893. *
  35894. * @method
  35895. * @param {Object3D} scene - The scene or 3D object to precompile.
  35896. * @param {Camera} camera - The camera that is used to render the scene.
  35897. * @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.
  35898. * @return {Promise} A Promise that resolves when the compile has been finished.
  35899. */
  35900. get compile() {
  35901. return this.compileAsync;
  35902. }
  35903. }
  35904. /**
  35905. * A binding represents the connection between a resource (like a texture, sampler
  35906. * or uniform buffer) and the resource definition in a shader stage.
  35907. *
  35908. * This module is an abstract base class for all concrete bindings types.
  35909. *
  35910. * @abstract
  35911. * @private
  35912. */
  35913. class Binding {
  35914. /**
  35915. * Constructs a new binding.
  35916. *
  35917. * @param {String} [name=''] - The binding's name.
  35918. */
  35919. constructor( name = '' ) {
  35920. /**
  35921. * The binding's name.
  35922. *
  35923. * @type {String}
  35924. */
  35925. this.name = name;
  35926. /**
  35927. * A bitmask that defines in what shader stages the
  35928. * binding's resource is accessible.
  35929. *
  35930. * @type {Number}
  35931. */
  35932. this.visibility = 0;
  35933. }
  35934. /**
  35935. * Makes sure binding's resource is visible for the given shader stage.
  35936. *
  35937. * @param {Number} visibility - The shader stage.
  35938. */
  35939. setVisibility( visibility ) {
  35940. this.visibility |= visibility;
  35941. }
  35942. /**
  35943. * Clones the binding.
  35944. *
  35945. * @return {Binding} The cloned binding.
  35946. */
  35947. clone() {
  35948. return Object.assign( new this.constructor(), this );
  35949. }
  35950. }
  35951. /** @module BufferUtils **/
  35952. /**
  35953. * This function is usually called with the length in bytes of an array buffer.
  35954. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  35955. *
  35956. * @function
  35957. * @param {Number} floatLength - The buffer length.
  35958. * @return {Number} The padded length.
  35959. */
  35960. function getFloatLength( floatLength ) {
  35961. // ensure chunk size alignment (STD140 layout)
  35962. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  35963. }
  35964. /**
  35965. * Represents a buffer binding type.
  35966. *
  35967. * @private
  35968. * @abstract
  35969. * @augments Binding
  35970. */
  35971. class Buffer extends Binding {
  35972. /**
  35973. * Constructs a new buffer.
  35974. *
  35975. * @param {String} name - The buffer's name.
  35976. * @param {TypedArray} [buffer=null] - The buffer.
  35977. */
  35978. constructor( name, buffer = null ) {
  35979. super( name );
  35980. /**
  35981. * This flag can be used for type testing.
  35982. *
  35983. * @type {Boolean}
  35984. * @readonly
  35985. * @default true
  35986. */
  35987. this.isBuffer = true;
  35988. /**
  35989. * The bytes per element.
  35990. *
  35991. * @type {Number}
  35992. */
  35993. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  35994. /**
  35995. * A reference to the internal buffer.
  35996. *
  35997. * @private
  35998. * @type {TypedArray}
  35999. */
  36000. this._buffer = buffer;
  36001. }
  36002. /**
  36003. * The buffer's byte length.
  36004. *
  36005. * @type {Number}
  36006. * @readonly
  36007. */
  36008. get byteLength() {
  36009. return getFloatLength( this._buffer.byteLength );
  36010. }
  36011. /**
  36012. * A reference to the internal buffer.
  36013. *
  36014. * @type {Float32Array}
  36015. * @readonly
  36016. */
  36017. get buffer() {
  36018. return this._buffer;
  36019. }
  36020. /**
  36021. * Updates the binding.
  36022. *
  36023. * @return {Boolean} Whether the buffer has been updated and must be
  36024. * uploaded to the GPU.
  36025. */
  36026. update() {
  36027. return true;
  36028. }
  36029. }
  36030. /**
  36031. * Represents a uniform buffer binding type.
  36032. *
  36033. * @private
  36034. * @augments Buffer
  36035. */
  36036. class UniformBuffer extends Buffer {
  36037. /**
  36038. * Constructs a new uniform buffer.
  36039. *
  36040. * @param {String} name - The buffer's name.
  36041. * @param {TypedArray} [buffer=null] - The buffer.
  36042. */
  36043. constructor( name, buffer = null ) {
  36044. super( name, buffer );
  36045. /**
  36046. * This flag can be used for type testing.
  36047. *
  36048. * @type {Boolean}
  36049. * @readonly
  36050. * @default true
  36051. */
  36052. this.isUniformBuffer = true;
  36053. }
  36054. }
  36055. let _id$4 = 0;
  36056. /**
  36057. * A special form of uniform buffer binding type.
  36058. * It's buffer value is managed by a node object.
  36059. *
  36060. * @private
  36061. * @augments UniformBuffer
  36062. */
  36063. class NodeUniformBuffer extends UniformBuffer {
  36064. /**
  36065. * Constructs a new node-based uniform buffer.
  36066. *
  36067. * @param {BufferNode} nodeUniform - The uniform buffer node.
  36068. * @param {UniformGroupNode} groupNode - The uniform group node.
  36069. */
  36070. constructor( nodeUniform, groupNode ) {
  36071. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  36072. /**
  36073. * The uniform buffer node.
  36074. *
  36075. * @type {BufferNode}
  36076. */
  36077. this.nodeUniform = nodeUniform;
  36078. /**
  36079. * The uniform group node.
  36080. *
  36081. * @type {UniformGroupNode}
  36082. */
  36083. this.groupNode = groupNode;
  36084. }
  36085. /**
  36086. * The uniform buffer.
  36087. *
  36088. * @type {Float32Array}
  36089. */
  36090. get buffer() {
  36091. return this.nodeUniform.value;
  36092. }
  36093. }
  36094. /**
  36095. * This class represents a uniform buffer binding but with
  36096. * an API that allows to maintain individual uniform objects.
  36097. *
  36098. * @private
  36099. * @augments UniformBuffer
  36100. */
  36101. class UniformsGroup extends UniformBuffer {
  36102. /**
  36103. * Constructs a new uniforms group.
  36104. *
  36105. * @param {String} name - The group's name.
  36106. */
  36107. constructor( name ) {
  36108. super( name );
  36109. /**
  36110. * This flag can be used for type testing.
  36111. *
  36112. * @type {Boolean}
  36113. * @readonly
  36114. * @default true
  36115. */
  36116. this.isUniformsGroup = true;
  36117. /**
  36118. * An array with the raw uniform values.
  36119. *
  36120. * @private
  36121. * @type {Array<Number>?}
  36122. * @default null
  36123. */
  36124. this._values = null;
  36125. /**
  36126. * An array of uniform objects.
  36127. *
  36128. * The order of uniforms in this array must match the order of uniforms in the shader.
  36129. *
  36130. * @type {Array<Uniform>}
  36131. */
  36132. this.uniforms = [];
  36133. }
  36134. /**
  36135. * Adds a uniform to this group.
  36136. *
  36137. * @param {Uniform} uniform - The uniform to add.
  36138. * @return {UniformsGroup} A reference to this group.
  36139. */
  36140. addUniform( uniform ) {
  36141. this.uniforms.push( uniform );
  36142. return this;
  36143. }
  36144. /**
  36145. * Removes a uniform from this group.
  36146. *
  36147. * @param {Uniform} uniform - The uniform to remove.
  36148. * @return {UniformsGroup} A reference to this group.
  36149. */
  36150. removeUniform( uniform ) {
  36151. const index = this.uniforms.indexOf( uniform );
  36152. if ( index !== -1 ) {
  36153. this.uniforms.splice( index, 1 );
  36154. }
  36155. return this;
  36156. }
  36157. /**
  36158. * An array with the raw uniform values.
  36159. *
  36160. * @type {Array<Number>}
  36161. */
  36162. get values() {
  36163. if ( this._values === null ) {
  36164. this._values = Array.from( this.buffer );
  36165. }
  36166. return this._values;
  36167. }
  36168. /**
  36169. * A Float32 array buffer with the uniform values.
  36170. *
  36171. * @type {Float32Array}
  36172. */
  36173. get buffer() {
  36174. let buffer = this._buffer;
  36175. if ( buffer === null ) {
  36176. const byteLength = this.byteLength;
  36177. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36178. this._buffer = buffer;
  36179. }
  36180. return buffer;
  36181. }
  36182. /**
  36183. * The byte length of the buffer with correct buffer alignment.
  36184. *
  36185. * @type {Number}
  36186. */
  36187. get byteLength() {
  36188. let offset = 0; // global buffer offset in bytes
  36189. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36190. const uniform = this.uniforms[ i ];
  36191. const { boundary, itemSize } = uniform;
  36192. // offset within a single chunk in bytes
  36193. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36194. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36195. // conformance tests
  36196. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36197. // check for chunk overflow
  36198. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36199. } else if ( chunkOffset % boundary !== 0 ) {
  36200. // check for correct alignment
  36201. offset += ( chunkOffset % boundary );
  36202. }
  36203. uniform.offset = ( offset / this.bytesPerElement );
  36204. offset += ( itemSize * this.bytesPerElement );
  36205. }
  36206. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36207. }
  36208. /**
  36209. * Updates this group by updating each uniform object of
  36210. * the internal uniform list. The uniform objects check if their
  36211. * values has actually changed so this method only returns
  36212. * `true` if there is a real value change.
  36213. *
  36214. * @return {Boolean} Whether the uniforms have been updated and
  36215. * must be uploaded to the GPU.
  36216. */
  36217. update() {
  36218. let updated = false;
  36219. for ( const uniform of this.uniforms ) {
  36220. if ( this.updateByType( uniform ) === true ) {
  36221. updated = true;
  36222. }
  36223. }
  36224. return updated;
  36225. }
  36226. /**
  36227. * Updates a given uniform by calling an update method matching
  36228. * the uniforms type.
  36229. *
  36230. * @param {Uniform} uniform - The uniform to update.
  36231. * @return {Boolean} Whether the uniform has been updated or not.
  36232. */
  36233. updateByType( uniform ) {
  36234. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36235. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36236. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36237. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36238. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36239. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36240. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36241. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36242. }
  36243. /**
  36244. * Updates a given Number uniform.
  36245. *
  36246. * @param {NumberUniform} uniform - The Number uniform.
  36247. * @return {Boolean} Whether the uniform has been updated or not.
  36248. */
  36249. updateNumber( uniform ) {
  36250. let updated = false;
  36251. const a = this.values;
  36252. const v = uniform.getValue();
  36253. const offset = uniform.offset;
  36254. const type = uniform.getType();
  36255. if ( a[ offset ] !== v ) {
  36256. const b = this._getBufferForType( type );
  36257. b[ offset ] = a[ offset ] = v;
  36258. updated = true;
  36259. }
  36260. return updated;
  36261. }
  36262. /**
  36263. * Updates a given Vector2 uniform.
  36264. *
  36265. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36266. * @return {Boolean} Whether the uniform has been updated or not.
  36267. */
  36268. updateVector2( uniform ) {
  36269. let updated = false;
  36270. const a = this.values;
  36271. const v = uniform.getValue();
  36272. const offset = uniform.offset;
  36273. const type = uniform.getType();
  36274. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36275. const b = this._getBufferForType( type );
  36276. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36277. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36278. updated = true;
  36279. }
  36280. return updated;
  36281. }
  36282. /**
  36283. * Updates a given Vector3 uniform.
  36284. *
  36285. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36286. * @return {Boolean} Whether the uniform has been updated or not.
  36287. */
  36288. updateVector3( uniform ) {
  36289. let updated = false;
  36290. const a = this.values;
  36291. const v = uniform.getValue();
  36292. const offset = uniform.offset;
  36293. const type = uniform.getType();
  36294. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36295. const b = this._getBufferForType( type );
  36296. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36297. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36298. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36299. updated = true;
  36300. }
  36301. return updated;
  36302. }
  36303. /**
  36304. * Updates a given Vector4 uniform.
  36305. *
  36306. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36307. * @return {Boolean} Whether the uniform has been updated or not.
  36308. */
  36309. updateVector4( uniform ) {
  36310. let updated = false;
  36311. const a = this.values;
  36312. const v = uniform.getValue();
  36313. const offset = uniform.offset;
  36314. const type = uniform.getType();
  36315. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36316. const b = this._getBufferForType( type );
  36317. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36318. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36319. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36320. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36321. updated = true;
  36322. }
  36323. return updated;
  36324. }
  36325. /**
  36326. * Updates a given Color uniform.
  36327. *
  36328. * @param {ColorUniform} uniform - The Color uniform.
  36329. * @return {Boolean} Whether the uniform has been updated or not.
  36330. */
  36331. updateColor( uniform ) {
  36332. let updated = false;
  36333. const a = this.values;
  36334. const c = uniform.getValue();
  36335. const offset = uniform.offset;
  36336. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36337. const b = this.buffer;
  36338. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36339. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36340. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36341. updated = true;
  36342. }
  36343. return updated;
  36344. }
  36345. /**
  36346. * Updates a given Matrix3 uniform.
  36347. *
  36348. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36349. * @return {Boolean} Whether the uniform has been updated or not.
  36350. */
  36351. updateMatrix3( uniform ) {
  36352. let updated = false;
  36353. const a = this.values;
  36354. const e = uniform.getValue().elements;
  36355. const offset = uniform.offset;
  36356. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36357. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36358. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36359. const b = this.buffer;
  36360. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36361. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36362. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36363. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36364. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36365. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36366. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36367. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36368. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36369. updated = true;
  36370. }
  36371. return updated;
  36372. }
  36373. /**
  36374. * Updates a given Matrix4 uniform.
  36375. *
  36376. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36377. * @return {Boolean} Whether the uniform has been updated or not.
  36378. */
  36379. updateMatrix4( uniform ) {
  36380. let updated = false;
  36381. const a = this.values;
  36382. const e = uniform.getValue().elements;
  36383. const offset = uniform.offset;
  36384. if ( arraysEqual( a, e, offset ) === false ) {
  36385. const b = this.buffer;
  36386. b.set( e, offset );
  36387. setArray( a, e, offset );
  36388. updated = true;
  36389. }
  36390. return updated;
  36391. }
  36392. /**
  36393. * Returns a typed array that matches the given data type.
  36394. *
  36395. * @param {String} type - The data type.
  36396. * @return {TypedArray} The typed array.
  36397. */
  36398. _getBufferForType( type ) {
  36399. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36400. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36401. return this.buffer;
  36402. }
  36403. }
  36404. /**
  36405. * Sets the values of the second array to the first array.
  36406. *
  36407. * @private
  36408. * @param {TypedArray} a - The first array.
  36409. * @param {TypedArray} b - The second array.
  36410. * @param {Number} offset - An index offset for the first array.
  36411. */
  36412. function setArray( a, b, offset ) {
  36413. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36414. a[ offset + i ] = b[ i ];
  36415. }
  36416. }
  36417. /**
  36418. * Returns `true` if the given arrays are equal.
  36419. *
  36420. * @private
  36421. * @param {TypedArray} a - The first array.
  36422. * @param {TypedArray} b - The second array.
  36423. * @param {Number} offset - An index offset for the first array.
  36424. * @return {Boolean} Whether the given arrays are equal or not.
  36425. */
  36426. function arraysEqual( a, b, offset ) {
  36427. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36428. if ( a[ offset + i ] !== b[ i ] ) return false;
  36429. }
  36430. return true;
  36431. }
  36432. let _id$3 = 0;
  36433. /**
  36434. * A special form of uniforms group that represents
  36435. * the individual uniforms as node-based uniforms.
  36436. *
  36437. * @private
  36438. * @augments UniformsGroup
  36439. */
  36440. class NodeUniformsGroup extends UniformsGroup {
  36441. /**
  36442. * Constructs a new node-based uniforms group.
  36443. *
  36444. * @param {String} name - The group's name.
  36445. * @param {UniformGroupNode} groupNode - The uniform group node.
  36446. */
  36447. constructor( name, groupNode ) {
  36448. super( name );
  36449. /**
  36450. * The group's ID.
  36451. *
  36452. * @type {Number}
  36453. */
  36454. this.id = _id$3 ++;
  36455. /**
  36456. * The uniform group node.
  36457. *
  36458. * @type {UniformGroupNode}
  36459. */
  36460. this.groupNode = groupNode;
  36461. /**
  36462. * This flag can be used for type testing.
  36463. *
  36464. * @type {Boolean}
  36465. * @readonly
  36466. * @default true
  36467. */
  36468. this.isNodeUniformsGroup = true;
  36469. }
  36470. }
  36471. let _id$2 = 0;
  36472. /**
  36473. * Represents a sampled texture binding type.
  36474. *
  36475. * @private
  36476. * @augments Binding
  36477. */
  36478. class SampledTexture extends Binding {
  36479. /**
  36480. * Constructs a new sampled texture.
  36481. *
  36482. * @param {String} name - The sampled texture's name.
  36483. * @param {Texture?} texture - The texture this binding is referring to.
  36484. */
  36485. constructor( name, texture ) {
  36486. super( name );
  36487. /**
  36488. * This identifier.
  36489. *
  36490. * @type {Number}
  36491. */
  36492. this.id = _id$2 ++;
  36493. /**
  36494. * The texture this binding is referring to.
  36495. *
  36496. * @type {Texture?}
  36497. */
  36498. this.texture = texture;
  36499. /**
  36500. * The binding's version.
  36501. *
  36502. * @type {Number}
  36503. */
  36504. this.version = texture ? texture.version : 0;
  36505. /**
  36506. * Whether the texture is a storage texture or not.
  36507. *
  36508. * @type {Boolean}
  36509. * @default false
  36510. */
  36511. this.store = false;
  36512. /**
  36513. * The binding's generation which is an additional version
  36514. * qualifier.
  36515. *
  36516. * @type {Number?}
  36517. * @default null
  36518. */
  36519. this.generation = null;
  36520. /**
  36521. * This flag can be used for type testing.
  36522. *
  36523. * @type {Boolean}
  36524. * @readonly
  36525. * @default true
  36526. */
  36527. this.isSampledTexture = true;
  36528. }
  36529. /**
  36530. * Returns `true` whether this binding requires an update for the
  36531. * given generation.
  36532. *
  36533. * @param {Number} generation - The generation.
  36534. * @return {Boolean} Whether an update is required or not.
  36535. */
  36536. needsBindingsUpdate( generation ) {
  36537. const { texture } = this;
  36538. if ( generation !== this.generation ) {
  36539. this.generation = generation;
  36540. return true;
  36541. }
  36542. return texture.isVideoTexture;
  36543. }
  36544. /**
  36545. * Updates the binding.
  36546. *
  36547. * @return {Boolean} Whether the texture has been updated and must be
  36548. * uploaded to the GPU.
  36549. */
  36550. update() {
  36551. const { texture, version } = this;
  36552. if ( version !== texture.version ) {
  36553. this.version = texture.version;
  36554. return true;
  36555. }
  36556. return false;
  36557. }
  36558. }
  36559. /**
  36560. * A special form of sampled texture binding type.
  36561. * It's texture value is managed by a node object.
  36562. *
  36563. * @private
  36564. * @augments SampledTexture
  36565. */
  36566. class NodeSampledTexture extends SampledTexture {
  36567. /**
  36568. * Constructs a new node-based sampled texture.
  36569. *
  36570. * @param {String} name - The textures's name.
  36571. * @param {TextureNode} textureNode - The texture node.
  36572. * @param {UniformGroupNode} groupNode - The uniform group node.
  36573. * @param {String?} [access=null] - The access type.
  36574. */
  36575. constructor( name, textureNode, groupNode, access = null ) {
  36576. super( name, textureNode ? textureNode.value : null );
  36577. /**
  36578. * The texture node.
  36579. *
  36580. * @type {TextureNode}
  36581. */
  36582. this.textureNode = textureNode;
  36583. /**
  36584. * The uniform group node.
  36585. *
  36586. * @type {UniformGroupNode}
  36587. */
  36588. this.groupNode = groupNode;
  36589. /**
  36590. * The access type.
  36591. *
  36592. * @type {String?}
  36593. * @default null
  36594. */
  36595. this.access = access;
  36596. }
  36597. /**
  36598. * Overwrites the default to additionally check if the node value has changed.
  36599. *
  36600. * @param {Number} generation - The generation.
  36601. * @return {Boolean} Whether an update is required or not.
  36602. */
  36603. needsBindingsUpdate( generation ) {
  36604. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  36605. }
  36606. /**
  36607. * Updates the binding.
  36608. *
  36609. * @return {Boolean} Whether the texture has been updated and must be
  36610. * uploaded to the GPU.
  36611. */
  36612. update() {
  36613. const { textureNode } = this;
  36614. if ( this.texture !== textureNode.value ) {
  36615. this.texture = textureNode.value;
  36616. return true;
  36617. }
  36618. return super.update();
  36619. }
  36620. }
  36621. /**
  36622. * A special form of sampled cube texture binding type.
  36623. * It's texture value is managed by a node object.
  36624. *
  36625. * @private
  36626. * @augments NodeSampledTexture
  36627. */
  36628. class NodeSampledCubeTexture extends NodeSampledTexture {
  36629. /**
  36630. * Constructs a new node-based sampled cube texture.
  36631. *
  36632. * @param {String} name - The textures's name.
  36633. * @param {TextureNode} textureNode - The texture node.
  36634. * @param {UniformGroupNode} groupNode - The uniform group node.
  36635. * @param {String?} [access=null] - The access type.
  36636. */
  36637. constructor( name, textureNode, groupNode, access = null ) {
  36638. super( name, textureNode, groupNode, access );
  36639. /**
  36640. * This flag can be used for type testing.
  36641. *
  36642. * @type {Boolean}
  36643. * @readonly
  36644. * @default true
  36645. */
  36646. this.isSampledCubeTexture = true;
  36647. }
  36648. }
  36649. /**
  36650. * A special form of sampled 3D texture binding type.
  36651. * It's texture value is managed by a node object.
  36652. *
  36653. * @private
  36654. * @augments NodeSampledTexture
  36655. */
  36656. class NodeSampledTexture3D extends NodeSampledTexture {
  36657. /**
  36658. * Constructs a new node-based sampled 3D texture.
  36659. *
  36660. * @param {String} name - The textures's name.
  36661. * @param {TextureNode} textureNode - The texture node.
  36662. * @param {UniformGroupNode} groupNode - The uniform group node.
  36663. * @param {String?} [access=null] - The access type.
  36664. */
  36665. constructor( name, textureNode, groupNode, access = null ) {
  36666. super( name, textureNode, groupNode, access );
  36667. /**
  36668. * This flag can be used for type testing.
  36669. *
  36670. * @type {Boolean}
  36671. * @readonly
  36672. * @default true
  36673. */
  36674. this.isSampledTexture3D = true;
  36675. }
  36676. }
  36677. const glslMethods = {
  36678. textureDimensions: 'textureSize',
  36679. equals: 'equal'
  36680. };
  36681. const precisionLib = {
  36682. low: 'lowp',
  36683. medium: 'mediump',
  36684. high: 'highp'
  36685. };
  36686. const supports$1 = {
  36687. swizzleAssign: true,
  36688. storageBuffer: false
  36689. };
  36690. const defaultPrecisions = `
  36691. precision highp float;
  36692. precision highp int;
  36693. precision highp sampler2D;
  36694. precision highp sampler3D;
  36695. precision highp samplerCube;
  36696. precision highp sampler2DArray;
  36697. precision highp usampler2D;
  36698. precision highp usampler3D;
  36699. precision highp usamplerCube;
  36700. precision highp usampler2DArray;
  36701. precision highp isampler2D;
  36702. precision highp isampler3D;
  36703. precision highp isamplerCube;
  36704. precision highp isampler2DArray;
  36705. precision lowp sampler2DShadow;
  36706. `;
  36707. /**
  36708. * A node builder targeting GLSL.
  36709. *
  36710. * This module generates GLSL shader code from node materials and also
  36711. * generates the respective bindings and vertex buffer definitions. These
  36712. * data are later used by the renderer to create render and compute pipelines
  36713. * for render objects.
  36714. *
  36715. * @augments NodeBuilder
  36716. */
  36717. class GLSLNodeBuilder extends NodeBuilder {
  36718. /**
  36719. * Constructs a new GLSL node builder renderer.
  36720. *
  36721. * @param {Object3D} object - The 3D object.
  36722. * @param {Renderer} renderer - The renderer.
  36723. */
  36724. constructor( object, renderer ) {
  36725. super( object, renderer, new GLSLNodeParser() );
  36726. /**
  36727. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  36728. * another dictionary which manages UBOs per group ('render','frame','object').
  36729. *
  36730. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  36731. */
  36732. this.uniformGroups = {};
  36733. /**
  36734. * An array that holds objects defining the varying and attribute data in
  36735. * context of Transform Feedback.
  36736. *
  36737. * @type {Object<String,Map<String,Object>>}
  36738. */
  36739. this.transforms = [];
  36740. /**
  36741. * A dictionary that holds for each shader stage a Map of used extensions.
  36742. *
  36743. * @type {Object<String,Map<String,Object>>}
  36744. */
  36745. this.extensions = {};
  36746. /**
  36747. * A dictionary that holds for each shader stage an Array of used builtins.
  36748. *
  36749. * @type {Object<String,Array<String>>}
  36750. */
  36751. this.builtins = { vertex: [], fragment: [], compute: [] };
  36752. /**
  36753. * Whether comparison in shader code are generated with methods or not.
  36754. *
  36755. * @type {Boolean}
  36756. * @default true
  36757. */
  36758. this.useComparisonMethod = true;
  36759. }
  36760. /**
  36761. * Checks if the given texture requires a manual conversion to the working color space.
  36762. *
  36763. * @param {Texture} texture - The texture to check.
  36764. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  36765. */
  36766. needsToWorkingColorSpace( texture ) {
  36767. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  36768. }
  36769. /**
  36770. * Returns the native shader method name for a given generic name.
  36771. *
  36772. * @param {String} method - The method name to resolve.
  36773. * @return {String} The resolved GLSL method name.
  36774. */
  36775. getMethod( method ) {
  36776. return glslMethods[ method ] || method;
  36777. }
  36778. /**
  36779. * Returns the output struct name. Not relevant for GLSL.
  36780. *
  36781. * @return {String}
  36782. */
  36783. getOutputStructName() {
  36784. return '';
  36785. }
  36786. /**
  36787. * Builds the given shader node.
  36788. *
  36789. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36790. * @return {String} The GLSL function code.
  36791. */
  36792. buildFunctionCode( shaderNode ) {
  36793. const layout = shaderNode.layout;
  36794. const flowData = this.flowShaderNode( shaderNode );
  36795. const parameters = [];
  36796. for ( const input of layout.inputs ) {
  36797. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36798. }
  36799. //
  36800. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36801. ${ flowData.vars }
  36802. ${ flowData.code }
  36803. return ${ flowData.result };
  36804. }`;
  36805. //
  36806. return code;
  36807. }
  36808. /**
  36809. * Setups the Pixel Buffer Object (PBO) for the given storage
  36810. * buffer node.
  36811. *
  36812. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  36813. */
  36814. setupPBO( storageBufferNode ) {
  36815. const attribute = storageBufferNode.value;
  36816. if ( attribute.pbo === undefined ) {
  36817. const originalArray = attribute.array;
  36818. const numElements = attribute.count * attribute.itemSize;
  36819. const { itemSize } = attribute;
  36820. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36821. let format = isInteger ? RedIntegerFormat : RedFormat;
  36822. if ( itemSize === 2 ) {
  36823. format = isInteger ? RGIntegerFormat : RGFormat;
  36824. } else if ( itemSize === 3 ) {
  36825. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36826. } else if ( itemSize === 4 ) {
  36827. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36828. }
  36829. const typeMap = {
  36830. Float32Array: FloatType,
  36831. Uint8Array: UnsignedByteType,
  36832. Uint16Array: UnsignedShortType,
  36833. Uint32Array: UnsignedIntType,
  36834. Int8Array: ByteType,
  36835. Int16Array: ShortType,
  36836. Int32Array: IntType,
  36837. Uint8ClampedArray: UnsignedByteType,
  36838. };
  36839. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36840. let height = Math.ceil( ( numElements / itemSize ) / width );
  36841. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36842. const newSize = width * height * itemSize;
  36843. const newArray = new originalArray.constructor( newSize );
  36844. newArray.set( originalArray, 0 );
  36845. attribute.array = newArray;
  36846. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36847. pboTexture.needsUpdate = true;
  36848. pboTexture.isPBOTexture = true;
  36849. const pbo = new TextureNode( pboTexture, null, null );
  36850. pbo.setPrecision( 'high' );
  36851. attribute.pboNode = pbo;
  36852. attribute.pbo = pbo.value;
  36853. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36854. }
  36855. }
  36856. /**
  36857. * Returns a GLSL snippet that represents the property name of the given node.
  36858. *
  36859. * @param {Node} node - The node.
  36860. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36861. * @return {String} The property name.
  36862. */
  36863. getPropertyName( node, shaderStage = this.shaderStage ) {
  36864. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36865. return shaderStage.charAt( 0 ) + '_' + node.name;
  36866. }
  36867. return super.getPropertyName( node, shaderStage );
  36868. }
  36869. /**
  36870. * Setups the Pixel Buffer Object (PBO) for the given storage
  36871. * buffer node.
  36872. *
  36873. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  36874. * @return {String} The property name.
  36875. */
  36876. generatePBO( storageArrayElementNode ) {
  36877. const { node, indexNode } = storageArrayElementNode;
  36878. const attribute = node.value;
  36879. if ( this.renderer.backend.has( attribute ) ) {
  36880. const attributeData = this.renderer.backend.get( attribute );
  36881. attributeData.pbo = attribute.pbo;
  36882. }
  36883. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36884. const textureName = this.getPropertyName( nodeUniform );
  36885. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  36886. const indexSnippet = indexNode.build( this, 'uint' );
  36887. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36888. let propertyName = elementNodeData.propertyName;
  36889. if ( propertyName === undefined ) {
  36890. // property element
  36891. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36892. propertyName = this.getPropertyName( nodeVar );
  36893. // property size
  36894. const bufferNodeData = this.getDataFromNode( node );
  36895. let propertySizeName = bufferNodeData.propertySizeName;
  36896. if ( propertySizeName === undefined ) {
  36897. propertySizeName = propertyName + 'Size';
  36898. this.getVarFromNode( node, propertySizeName, 'uint' );
  36899. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  36900. bufferNodeData.propertySizeName = propertySizeName;
  36901. }
  36902. //
  36903. const { itemSize } = attribute;
  36904. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36905. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36906. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36907. //
  36908. let prefix = 'vec4';
  36909. if ( attribute.pbo.type === UnsignedIntType ) {
  36910. prefix = 'uvec4';
  36911. } else if ( attribute.pbo.type === IntType ) {
  36912. prefix = 'ivec4';
  36913. }
  36914. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  36915. elementNodeData.propertyName = propertyName;
  36916. }
  36917. return propertyName;
  36918. }
  36919. /**
  36920. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  36921. *
  36922. * @param {Texture} texture - The texture.
  36923. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36924. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36925. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36926. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36927. * @return {String} The GLSL snippet.
  36928. */
  36929. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36930. if ( depthSnippet ) {
  36931. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36932. } else {
  36933. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36934. }
  36935. }
  36936. /**
  36937. * Generates the GLSL snippet for sampling/loading the given texture.
  36938. *
  36939. * @param {Texture} texture - The texture.
  36940. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36941. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36942. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36943. * @return {String} The GLSL snippet.
  36944. */
  36945. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36946. if ( texture.isDepthTexture ) {
  36947. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36948. } else {
  36949. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36950. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36951. }
  36952. }
  36953. /**
  36954. * Generates the GLSL snippet when sampling textures with explicit mip level.
  36955. *
  36956. * @param {Texture} texture - The texture.
  36957. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36958. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36959. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36960. * @return {String} The GLSL snippet.
  36961. */
  36962. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36963. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36964. }
  36965. /**
  36966. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  36967. *
  36968. * @param {Texture} texture - The texture.
  36969. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36970. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36971. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  36972. * @return {String} The GLSL snippet.
  36973. */
  36974. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  36975. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  36976. }
  36977. /**
  36978. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  36979. *
  36980. * @param {Texture} texture - The texture.
  36981. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36982. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36983. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  36984. * @return {String} The GLSL snippet.
  36985. */
  36986. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36987. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36988. }
  36989. /**
  36990. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  36991. * against a reference value.
  36992. *
  36993. * @param {Texture} texture - The texture.
  36994. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36995. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36996. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  36997. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  36998. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36999. * @return {String} The GLSL snippet.
  37000. */
  37001. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37002. if ( shaderStage === 'fragment' ) {
  37003. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37004. } else {
  37005. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37006. }
  37007. }
  37008. /**
  37009. * Returns the variables of the given shader stage as a GLSL string.
  37010. *
  37011. * @param {String} shaderStage - The shader stage.
  37012. * @return {String} The GLSL snippet that defines the variables.
  37013. */
  37014. getVars( shaderStage ) {
  37015. const snippets = [];
  37016. const vars = this.vars[ shaderStage ];
  37017. if ( vars !== undefined ) {
  37018. for ( const variable of vars ) {
  37019. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  37020. }
  37021. }
  37022. return snippets.join( '\n\t' );
  37023. }
  37024. /**
  37025. * Returns the uniforms of the given shader stage as a GLSL string.
  37026. *
  37027. * @param {String} shaderStage - The shader stage.
  37028. * @return {String} The GLSL snippet that defines the uniforms.
  37029. */
  37030. getUniforms( shaderStage ) {
  37031. const uniforms = this.uniforms[ shaderStage ];
  37032. const bindingSnippets = [];
  37033. const uniformGroups = {};
  37034. for ( const uniform of uniforms ) {
  37035. let snippet = null;
  37036. let group = false;
  37037. if ( uniform.type === 'texture' ) {
  37038. const texture = uniform.node.value;
  37039. let typePrefix = '';
  37040. if ( texture.isDataTexture === true ) {
  37041. if ( texture.type === UnsignedIntType ) {
  37042. typePrefix = 'u';
  37043. } else if ( texture.type === IntType ) {
  37044. typePrefix = 'i';
  37045. }
  37046. }
  37047. if ( texture.compareFunction ) {
  37048. snippet = `sampler2DShadow ${ uniform.name };`;
  37049. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37050. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37051. } else {
  37052. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37053. }
  37054. } else if ( uniform.type === 'cubeTexture' ) {
  37055. snippet = `samplerCube ${ uniform.name };`;
  37056. } else if ( uniform.type === 'texture3D' ) {
  37057. snippet = `sampler3D ${ uniform.name };`;
  37058. } else if ( uniform.type === 'buffer' ) {
  37059. const bufferNode = uniform.node;
  37060. const bufferType = this.getType( bufferNode.bufferType );
  37061. const bufferCount = bufferNode.bufferCount;
  37062. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37063. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37064. } else {
  37065. const vectorType = this.getVectorType( uniform.type );
  37066. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37067. group = true;
  37068. }
  37069. const precision = uniform.node.precision;
  37070. if ( precision !== null ) {
  37071. snippet = precisionLib[ precision ] + ' ' + snippet;
  37072. }
  37073. if ( group ) {
  37074. snippet = '\t' + snippet;
  37075. const groupName = uniform.groupNode.name;
  37076. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37077. groupSnippets.push( snippet );
  37078. } else {
  37079. snippet = 'uniform ' + snippet;
  37080. bindingSnippets.push( snippet );
  37081. }
  37082. }
  37083. let output = '';
  37084. for ( const name in uniformGroups ) {
  37085. const groupSnippets = uniformGroups[ name ];
  37086. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37087. }
  37088. output += bindingSnippets.join( '\n' );
  37089. return output;
  37090. }
  37091. /**
  37092. * Returns the type for a given buffer attribute.
  37093. *
  37094. * @param {BufferAttribute} attribute - The buffer attribute.
  37095. * @return {String} The type.
  37096. */
  37097. getTypeFromAttribute( attribute ) {
  37098. let nodeType = super.getTypeFromAttribute( attribute );
  37099. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37100. let dataAttribute = attribute;
  37101. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37102. const array = dataAttribute.array;
  37103. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37104. nodeType = nodeType.slice( 1 );
  37105. }
  37106. }
  37107. return nodeType;
  37108. }
  37109. /**
  37110. * Returns the shader attributes of the given shader stage as a GLSL string.
  37111. *
  37112. * @param {String} shaderStage - The shader stage.
  37113. * @return {String} The GLSL snippet that defines the shader attributes.
  37114. */
  37115. getAttributes( shaderStage ) {
  37116. let snippet = '';
  37117. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37118. const attributes = this.getAttributesArray();
  37119. let location = 0;
  37120. for ( const attribute of attributes ) {
  37121. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37122. }
  37123. }
  37124. return snippet;
  37125. }
  37126. /**
  37127. * Returns the members of the given struct type node as a GLSL string.
  37128. *
  37129. * @param {StructTypeNode} struct - The struct type node.
  37130. * @return {String} The GLSL snippet that defines the struct members.
  37131. */
  37132. getStructMembers( struct ) {
  37133. const snippets = [];
  37134. const members = struct.getMemberTypes();
  37135. for ( let i = 0; i < members.length; i ++ ) {
  37136. const member = members[ i ];
  37137. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37138. }
  37139. return snippets.join( '\n' );
  37140. }
  37141. /**
  37142. * Returns the structs of the given shader stage as a GLSL string.
  37143. *
  37144. * @param {String} shaderStage - The shader stage.
  37145. * @return {String} The GLSL snippet that defines the structs.
  37146. */
  37147. getStructs( shaderStage ) {
  37148. const snippets = [];
  37149. const structs = this.structs[ shaderStage ];
  37150. if ( structs.length === 0 ) {
  37151. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37152. }
  37153. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37154. const struct = structs[ index ];
  37155. let snippet = '\n';
  37156. snippet += this.getStructMembers( struct );
  37157. snippet += '\n';
  37158. snippets.push( snippet );
  37159. }
  37160. return snippets.join( '\n\n' );
  37161. }
  37162. /**
  37163. * Returns the varyings of the given shader stage as a GLSL string.
  37164. *
  37165. * @param {String} shaderStage - The shader stage.
  37166. * @return {String} The GLSL snippet that defines the varyings.
  37167. */
  37168. getVaryings( shaderStage ) {
  37169. let snippet = '';
  37170. const varyings = this.varyings;
  37171. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37172. for ( const varying of varyings ) {
  37173. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37174. const type = this.getType( varying.type );
  37175. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37176. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37177. }
  37178. } else if ( shaderStage === 'fragment' ) {
  37179. for ( const varying of varyings ) {
  37180. if ( varying.needsInterpolation ) {
  37181. const type = this.getType( varying.type );
  37182. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37183. snippet += `${flat}in ${type} ${varying.name};\n`;
  37184. }
  37185. }
  37186. }
  37187. for ( const builtin of this.builtins[ shaderStage ] ) {
  37188. snippet += `${builtin};\n`;
  37189. }
  37190. return snippet;
  37191. }
  37192. /**
  37193. * Returns the vertex index builtin.
  37194. *
  37195. * @return {String} The vertex index.
  37196. */
  37197. getVertexIndex() {
  37198. return 'uint( gl_VertexID )';
  37199. }
  37200. /**
  37201. * Returns the instance index builtin.
  37202. *
  37203. * @return {String} The instance index.
  37204. */
  37205. getInstanceIndex() {
  37206. return 'uint( gl_InstanceID )';
  37207. }
  37208. /**
  37209. * Returns the invocation local index builtin.
  37210. *
  37211. * @return {String} The invocation local index.
  37212. */
  37213. getInvocationLocalIndex() {
  37214. const workgroupSize = this.object.workgroupSize;
  37215. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37216. return `uint( gl_InstanceID ) % ${size}u`;
  37217. }
  37218. /**
  37219. * Returns the draw index builtin.
  37220. *
  37221. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37222. */
  37223. getDrawIndex() {
  37224. const extensions = this.renderer.backend.extensions;
  37225. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37226. return 'uint( gl_DrawID )';
  37227. }
  37228. return null;
  37229. }
  37230. /**
  37231. * Returns the front facing builtin.
  37232. *
  37233. * @return {String} The front facing builtin.
  37234. */
  37235. getFrontFacing() {
  37236. return 'gl_FrontFacing';
  37237. }
  37238. /**
  37239. * Returns the frag coord builtin.
  37240. *
  37241. * @return {String} The frag coord builtin.
  37242. */
  37243. getFragCoord() {
  37244. return 'gl_FragCoord.xy';
  37245. }
  37246. /**
  37247. * Returns the frag depth builtin.
  37248. *
  37249. * @return {String} The frag depth builtin.
  37250. */
  37251. getFragDepth() {
  37252. return 'gl_FragDepth';
  37253. }
  37254. /**
  37255. * Enables the given extension.
  37256. *
  37257. * @param {String} name - The extension name.
  37258. * @param {String} behavior - The extension behavior.
  37259. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37260. */
  37261. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37262. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37263. if ( map.has( name ) === false ) {
  37264. map.set( name, {
  37265. name,
  37266. behavior
  37267. } );
  37268. }
  37269. }
  37270. /**
  37271. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37272. *
  37273. * @param {String} shaderStage - The shader stage.
  37274. * @return {String} The GLSL snippet that defines the enabled extensions.
  37275. */
  37276. getExtensions( shaderStage ) {
  37277. const snippets = [];
  37278. if ( shaderStage === 'vertex' ) {
  37279. const ext = this.renderer.backend.extensions;
  37280. const isBatchedMesh = this.object.isBatchedMesh;
  37281. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37282. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37283. }
  37284. }
  37285. const extensions = this.extensions[ shaderStage ];
  37286. if ( extensions !== undefined ) {
  37287. for ( const { name, behavior } of extensions.values() ) {
  37288. snippets.push( `#extension ${name} : ${behavior}` );
  37289. }
  37290. }
  37291. return snippets.join( '\n' );
  37292. }
  37293. /**
  37294. * Returns the clip distances builtin.
  37295. *
  37296. * @return {String} The clip distances builtin.
  37297. */
  37298. getClipDistance() {
  37299. return 'gl_ClipDistance';
  37300. }
  37301. /**
  37302. * Whether the requested feature is available or not.
  37303. *
  37304. * @param {String} name - The requested feature.
  37305. * @return {Boolean} Whether the requested feature is supported or not.
  37306. */
  37307. isAvailable( name ) {
  37308. let result = supports$1[ name ];
  37309. if ( result === undefined ) {
  37310. let extensionName;
  37311. result = false;
  37312. switch ( name ) {
  37313. case 'float32Filterable':
  37314. extensionName = 'OES_texture_float_linear';
  37315. break;
  37316. case 'clipDistance':
  37317. extensionName = 'WEBGL_clip_cull_distance';
  37318. break;
  37319. }
  37320. if ( extensionName !== undefined ) {
  37321. const extensions = this.renderer.backend.extensions;
  37322. if ( extensions.has( extensionName ) ) {
  37323. extensions.get( extensionName );
  37324. result = true;
  37325. }
  37326. }
  37327. supports$1[ name ] = result;
  37328. }
  37329. return result;
  37330. }
  37331. /**
  37332. * Whether to flip texture data along its vertical axis or not.
  37333. *
  37334. * @return {Boolean} Returns always `true` in context of GLSL.
  37335. */
  37336. isFlipY() {
  37337. return true;
  37338. }
  37339. /**
  37340. * Enables hardware clipping.
  37341. *
  37342. * @param {String} planeCount - The clipping plane count.
  37343. */
  37344. enableHardwareClipping( planeCount ) {
  37345. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37346. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37347. }
  37348. /**
  37349. * Registers a transform in context of Transform Feedback.
  37350. *
  37351. * @param {String} varyingName - The varying name.
  37352. * @param {AttributeNode} attributeNode - The attribute node.
  37353. */
  37354. registerTransform( varyingName, attributeNode ) {
  37355. this.transforms.push( { varyingName, attributeNode } );
  37356. }
  37357. /**
  37358. * Returns the transforms of the given shader stage as a GLSL string.
  37359. *
  37360. * @param {String} shaderStage - The shader stage.
  37361. * @return {String} The GLSL snippet that defines the transforms.
  37362. */
  37363. getTransforms( /* shaderStage */ ) {
  37364. const transforms = this.transforms;
  37365. let snippet = '';
  37366. for ( let i = 0; i < transforms.length; i ++ ) {
  37367. const transform = transforms[ i ];
  37368. const attributeName = this.getPropertyName( transform.attributeNode );
  37369. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37370. }
  37371. return snippet;
  37372. }
  37373. /**
  37374. * Returns a GLSL struct based on the given name and variables.
  37375. *
  37376. * @private
  37377. * @param {String} name - The struct name.
  37378. * @param {String} vars - The struct variables.
  37379. * @return {String} The GLSL snippet representing a struct.
  37380. */
  37381. _getGLSLUniformStruct( name, vars ) {
  37382. return `
  37383. layout( std140 ) uniform ${name} {
  37384. ${vars}
  37385. };`;
  37386. }
  37387. /**
  37388. * Returns a GLSL vertex shader based on the given shader data.
  37389. *
  37390. * @private
  37391. * @param {Object} shaderData - The shader data.
  37392. * @return {String} The vertex shader.
  37393. */
  37394. _getGLSLVertexCode( shaderData ) {
  37395. return `#version 300 es
  37396. ${ this.getSignature() }
  37397. // extensions
  37398. ${shaderData.extensions}
  37399. // precision
  37400. ${ defaultPrecisions }
  37401. // uniforms
  37402. ${shaderData.uniforms}
  37403. // varyings
  37404. ${shaderData.varyings}
  37405. // attributes
  37406. ${shaderData.attributes}
  37407. // codes
  37408. ${shaderData.codes}
  37409. void main() {
  37410. // vars
  37411. ${shaderData.vars}
  37412. // transforms
  37413. ${shaderData.transforms}
  37414. // flow
  37415. ${shaderData.flow}
  37416. gl_PointSize = 1.0;
  37417. }
  37418. `;
  37419. }
  37420. /**
  37421. * Returns a GLSL fragment shader based on the given shader data.
  37422. *
  37423. * @private
  37424. * @param {Object} shaderData - The shader data.
  37425. * @return {String} The vertex shader.
  37426. */
  37427. _getGLSLFragmentCode( shaderData ) {
  37428. return `#version 300 es
  37429. ${ this.getSignature() }
  37430. // precision
  37431. ${ defaultPrecisions }
  37432. // uniforms
  37433. ${shaderData.uniforms}
  37434. // varyings
  37435. ${shaderData.varyings}
  37436. // codes
  37437. ${shaderData.codes}
  37438. ${shaderData.structs}
  37439. void main() {
  37440. // vars
  37441. ${shaderData.vars}
  37442. // flow
  37443. ${shaderData.flow}
  37444. }
  37445. `;
  37446. }
  37447. /**
  37448. * Controls the code build of the shader stages.
  37449. */
  37450. buildCode() {
  37451. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37452. this.sortBindingGroups();
  37453. for ( const shaderStage in shadersData ) {
  37454. let flow = '// code\n\n';
  37455. flow += this.flowCode[ shaderStage ];
  37456. const flowNodes = this.flowNodes[ shaderStage ];
  37457. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37458. for ( const node of flowNodes ) {
  37459. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37460. const slotName = node.name;
  37461. if ( slotName ) {
  37462. if ( flow.length > 0 ) flow += '\n';
  37463. flow += `\t// flow -> ${ slotName }\n\t`;
  37464. }
  37465. flow += `${ flowSlotData.code }\n\t`;
  37466. if ( node === mainNode && shaderStage !== 'compute' ) {
  37467. flow += '// result\n\t';
  37468. if ( shaderStage === 'vertex' ) {
  37469. flow += 'gl_Position = ';
  37470. flow += `${ flowSlotData.result };`;
  37471. } else if ( shaderStage === 'fragment' ) {
  37472. if ( ! node.outputNode.isOutputStructNode ) {
  37473. flow += 'fragColor = ';
  37474. flow += `${ flowSlotData.result };`;
  37475. }
  37476. }
  37477. }
  37478. }
  37479. const stageData = shadersData[ shaderStage ];
  37480. stageData.extensions = this.getExtensions( shaderStage );
  37481. stageData.uniforms = this.getUniforms( shaderStage );
  37482. stageData.attributes = this.getAttributes( shaderStage );
  37483. stageData.varyings = this.getVaryings( shaderStage );
  37484. stageData.vars = this.getVars( shaderStage );
  37485. stageData.structs = this.getStructs( shaderStage );
  37486. stageData.codes = this.getCodes( shaderStage );
  37487. stageData.transforms = this.getTransforms( shaderStage );
  37488. stageData.flow = flow;
  37489. }
  37490. if ( this.material !== null ) {
  37491. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37492. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37493. } else {
  37494. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37495. }
  37496. }
  37497. /**
  37498. * This method is one of the more important ones since it's responsible
  37499. * for generating a matching binding instance for the given uniform node.
  37500. *
  37501. * These bindings are later used in the renderer to create bind groups
  37502. * and layouts.
  37503. *
  37504. * @param {UniformNode} node - The uniform node.
  37505. * @param {String} type - The node data type.
  37506. * @param {String} shaderStage - The shader stage.
  37507. * @param {String?} [name=null] - An optional uniform name.
  37508. * @return {NodeUniform} The node uniform object.
  37509. */
  37510. getUniformFromNode( node, type, shaderStage, name = null ) {
  37511. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37512. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37513. let uniformGPU = nodeData.uniformGPU;
  37514. if ( uniformGPU === undefined ) {
  37515. const group = node.groupNode;
  37516. const groupName = group.name;
  37517. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37518. if ( type === 'texture' ) {
  37519. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37520. bindings.push( uniformGPU );
  37521. } else if ( type === 'cubeTexture' ) {
  37522. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37523. bindings.push( uniformGPU );
  37524. } else if ( type === 'texture3D' ) {
  37525. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37526. bindings.push( uniformGPU );
  37527. } else if ( type === 'buffer' ) {
  37528. node.name = `NodeBuffer_${ node.id }`;
  37529. uniformNode.name = `buffer${ node.id }`;
  37530. const buffer = new NodeUniformBuffer( node, group );
  37531. buffer.name = node.name;
  37532. bindings.push( buffer );
  37533. uniformGPU = buffer;
  37534. } else {
  37535. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37536. let uniformsGroup = uniformsStage[ groupName ];
  37537. if ( uniformsGroup === undefined ) {
  37538. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37539. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37540. uniformsStage[ groupName ] = uniformsGroup;
  37541. bindings.push( uniformsGroup );
  37542. }
  37543. uniformGPU = this.getNodeUniform( uniformNode, type );
  37544. uniformsGroup.addUniform( uniformGPU );
  37545. }
  37546. nodeData.uniformGPU = uniformGPU;
  37547. }
  37548. return uniformNode;
  37549. }
  37550. }
  37551. let _vector2 = null;
  37552. let _color4 = null;
  37553. /**
  37554. * Most of the rendering related logic is implemented in the
  37555. * {@link module:Renderer} module and related management components.
  37556. * Sometimes it is required though to execute commands which are
  37557. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  37558. * This abstract base class defines an interface that encapsulates
  37559. * all backend-related logic. Derived classes for each backend must
  37560. * implement the interface.
  37561. *
  37562. * @abstract
  37563. * @private
  37564. */
  37565. class Backend {
  37566. /**
  37567. * Constructs a new backend.
  37568. *
  37569. * @param {Object} parameters - An object holding parameters for the backend.
  37570. */
  37571. constructor( parameters = {} ) {
  37572. /**
  37573. * The parameters of the backend.
  37574. *
  37575. * @type {Object}
  37576. */
  37577. this.parameters = Object.assign( {}, parameters );
  37578. /**
  37579. * This weak map holds backend-specific data of objects
  37580. * like textures, attributes or render targets.
  37581. *
  37582. * @type {WeakMap}
  37583. */
  37584. this.data = new WeakMap();
  37585. /**
  37586. * A reference to the renderer.
  37587. *
  37588. * @type {Renderer?}
  37589. * @default null
  37590. */
  37591. this.renderer = null;
  37592. /**
  37593. * A reference to the canvas element the renderer is drawing to.
  37594. *
  37595. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  37596. * @default null
  37597. */
  37598. this.domElement = null;
  37599. }
  37600. /**
  37601. * Initializes the backend so it is ready for usage. Concrete backends
  37602. * are supposed to implement their rendering context creation and related
  37603. * operations in this method.
  37604. *
  37605. * @async
  37606. * @param {Renderer} renderer - The renderer.
  37607. * @return {Promise} A Promise that resolves when the backend has been initialized.
  37608. */
  37609. async init( renderer ) {
  37610. this.renderer = renderer;
  37611. }
  37612. /**
  37613. * The coordinate system of the backend.
  37614. *
  37615. * @abstract
  37616. * @type {Number}
  37617. * @readonly
  37618. */
  37619. get coordinateSystem() {}
  37620. // render context
  37621. /**
  37622. * This method is executed at the beginning of a render call and
  37623. * can be used by the backend to prepare the state for upcoming
  37624. * draw calls.
  37625. *
  37626. * @abstract
  37627. * @param {RenderContext} renderContext - The render context.
  37628. */
  37629. beginRender( /*renderContext*/ ) {}
  37630. /**
  37631. * This method is executed at the end of a render call and
  37632. * can be used by the backend to finalize work after draw
  37633. * calls.
  37634. *
  37635. * @abstract
  37636. * @param {RenderContext} renderContext - The render context.
  37637. */
  37638. finishRender( /*renderContext*/ ) {}
  37639. /**
  37640. * This method is executed at the beginning of a compute call and
  37641. * can be used by the backend to prepare the state for upcoming
  37642. * compute tasks.
  37643. *
  37644. * @abstract
  37645. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37646. */
  37647. beginCompute( /*computeGroup*/ ) {}
  37648. /**
  37649. * This method is executed at the end of a compute call and
  37650. * can be used by the backend to finalize work after compute
  37651. * tasks.
  37652. *
  37653. * @abstract
  37654. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37655. */
  37656. finishCompute( /*computeGroup*/ ) {}
  37657. // render object
  37658. /**
  37659. * Executes a draw command for the given render object.
  37660. *
  37661. * @abstract
  37662. * @param {RenderObject} renderObject - The render object to draw.
  37663. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  37664. */
  37665. draw( /*renderObject, info*/ ) { }
  37666. // compute node
  37667. /**
  37668. * Executes a compute command for the given compute node.
  37669. *
  37670. * @abstract
  37671. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  37672. * @param {Node} computeNode - The compute node.
  37673. * @param {Array<BindGroup>} bindings - The bindings.
  37674. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37675. */
  37676. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  37677. // program
  37678. /**
  37679. * Creates a shader program from the given programmable stage.
  37680. *
  37681. * @abstract
  37682. * @param {ProgrammableStage} program - The programmable stage.
  37683. */
  37684. createProgram( /*program*/ ) { }
  37685. /**
  37686. * Destroys the shader program of the given programmable stage.
  37687. *
  37688. * @abstract
  37689. * @param {ProgrammableStage} program - The programmable stage.
  37690. */
  37691. destroyProgram( /*program*/ ) { }
  37692. // bindings
  37693. /**
  37694. * Creates bindings from the given bind group definition.
  37695. *
  37696. * @abstract
  37697. * @param {BindGroup} bindGroup - The bind group.
  37698. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37699. * @param {Number} cacheIndex - The cache index.
  37700. * @param {Number} version - The version.
  37701. */
  37702. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37703. /**
  37704. * Updates the given bind group definition.
  37705. *
  37706. * @abstract
  37707. * @param {BindGroup} bindGroup - The bind group.
  37708. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37709. * @param {Number} cacheIndex - The cache index.
  37710. * @param {Number} version - The version.
  37711. */
  37712. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37713. /**
  37714. * Updates a buffer binding.
  37715. *
  37716. * @abstract
  37717. * @param {Buffer} binding - The buffer binding to update.
  37718. */
  37719. updateBinding( /*binding*/ ) { }
  37720. // pipeline
  37721. /**
  37722. * Creates a render pipeline for the given render object.
  37723. *
  37724. * @abstract
  37725. * @param {RenderObject} renderObject - The render object.
  37726. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  37727. */
  37728. createRenderPipeline( /*renderObject, promises*/ ) { }
  37729. /**
  37730. * Creates a compute pipeline for the given compute node.
  37731. *
  37732. * @abstract
  37733. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37734. * @param {Array<BindGroup>} bindings - The bindings.
  37735. */
  37736. createComputePipeline( /*computePipeline, bindings*/ ) { }
  37737. // cache key
  37738. /**
  37739. * Returns `true` if the render pipeline requires an update.
  37740. *
  37741. * @abstract
  37742. * @param {RenderObject} renderObject - The render object.
  37743. * @return {Boolean} Whether the render pipeline requires an update or not.
  37744. */
  37745. needsRenderUpdate( /*renderObject*/ ) { }
  37746. /**
  37747. * Returns a cache key that is used to identify render pipelines.
  37748. *
  37749. * @abstract
  37750. * @param {RenderObject} renderObject - The render object.
  37751. * @return {String} The cache key.
  37752. */
  37753. getRenderCacheKey( /*renderObject*/ ) { }
  37754. // node builder
  37755. /**
  37756. * Returns a node builder for the given render object.
  37757. *
  37758. * @abstract
  37759. * @param {RenderObject} renderObject - The render object.
  37760. * @param {Renderer} renderer - The renderer.
  37761. * @return {NodeBuilder} The node builder.
  37762. */
  37763. createNodeBuilder( /*renderObject, renderer*/ ) { }
  37764. // textures
  37765. /**
  37766. * Creates a GPU sampler for the given texture.
  37767. *
  37768. * @abstract
  37769. * @param {Texture} texture - The texture to create the sampler for.
  37770. */
  37771. createSampler( /*texture*/ ) { }
  37772. /**
  37773. * Destroys the GPU sampler for the given texture.
  37774. *
  37775. * @abstract
  37776. * @param {Texture} texture - The texture to destroy the sampler for.
  37777. */
  37778. destroySampler( /*texture*/ ) {}
  37779. /**
  37780. * Creates a default texture for the given texture that can be used
  37781. * as a placeholder until the actual texture is ready for usage.
  37782. *
  37783. * @abstract
  37784. * @param {Texture} texture - The texture to create a default texture for.
  37785. */
  37786. createDefaultTexture( /*texture*/ ) { }
  37787. /**
  37788. * Defines a texture on the GPU for the given texture object.
  37789. *
  37790. * @abstract
  37791. * @param {Texture} texture - The texture.
  37792. * @param {Object} [options={}] - Optional configuration parameter.
  37793. */
  37794. createTexture( /*texture, options={}*/ ) { }
  37795. /**
  37796. * Uploads the updated texture data to the GPU.
  37797. *
  37798. * @abstract
  37799. * @param {Texture} texture - The texture.
  37800. * @param {Object} [options={}] - Optional configuration parameter.
  37801. */
  37802. updateTexture( /*texture, options = {}*/ ) { }
  37803. /**
  37804. * Generates mipmaps for the given texture.
  37805. *
  37806. * @abstract
  37807. * @param {Texture} texture - The texture.
  37808. */
  37809. generateMipmaps( /*texture*/ ) { }
  37810. /**
  37811. * Destroys the GPU data for the given texture object.
  37812. *
  37813. * @abstract
  37814. * @param {Texture} texture - The texture.
  37815. */
  37816. destroyTexture( /*texture*/ ) { }
  37817. /**
  37818. * Returns texture data as a typed array.
  37819. *
  37820. * @abstract
  37821. * @async
  37822. * @param {Texture} texture - The texture to copy.
  37823. * @param {Number} x - The x coordinate of the copy origin.
  37824. * @param {Number} y - The y coordinate of the copy origin.
  37825. * @param {Number} width - The width of the copy.
  37826. * @param {Number} height - The height of the copy.
  37827. * @param {Number} faceIndex - The face index.
  37828. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  37829. */
  37830. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  37831. /**
  37832. * Copies data of the given source texture to the given destination texture.
  37833. *
  37834. * @abstract
  37835. * @param {Texture} srcTexture - The source texture.
  37836. * @param {Texture} dstTexture - The destination texture.
  37837. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  37838. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  37839. * @param {Number} [level=0] - The mip level to copy.
  37840. */
  37841. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  37842. /**
  37843. * Copies the current bound framebuffer to the given texture.
  37844. *
  37845. * @abstract
  37846. * @param {Texture} texture - The destination texture.
  37847. * @param {RenderContext} renderContext - The render context.
  37848. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  37849. */
  37850. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  37851. // attributes
  37852. /**
  37853. * Creates the GPU buffer of a shader attribute.
  37854. *
  37855. * @abstract
  37856. * @param {BufferAttribute} attribute - The buffer attribute.
  37857. */
  37858. createAttribute( /*attribute*/ ) { }
  37859. /**
  37860. * Creates the GPU buffer of an indexed shader attribute.
  37861. *
  37862. * @abstract
  37863. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  37864. */
  37865. createIndexAttribute( /*attribute*/ ) { }
  37866. /**
  37867. * Creates the GPU buffer of a storage attribute.
  37868. *
  37869. * @abstract
  37870. * @param {BufferAttribute} attribute - The buffer attribute.
  37871. */
  37872. createStorageAttribute( /*attribute*/ ) { }
  37873. /**
  37874. * Updates the GPU buffer of a shader attribute.
  37875. *
  37876. * @abstract
  37877. * @param {BufferAttribute} attribute - The buffer attribute to update.
  37878. */
  37879. updateAttribute( /*attribute*/ ) { }
  37880. /**
  37881. * Destroys the GPU buffer of a shader attribute.
  37882. *
  37883. * @abstract
  37884. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  37885. */
  37886. destroyAttribute( /*attribute*/ ) { }
  37887. // canvas
  37888. /**
  37889. * Returns the backend's rendering context.
  37890. *
  37891. * @abstract
  37892. * @return {Object} The rendering context.
  37893. */
  37894. getContext() { }
  37895. /**
  37896. * Backends can use this method if they have to run
  37897. * logic when the renderer gets resized.
  37898. *
  37899. * @abstract
  37900. */
  37901. updateSize() { }
  37902. /**
  37903. * Updates the viewport with the values from the given render context.
  37904. *
  37905. * @abstract
  37906. * @param {RenderContext} renderContext - The render context.
  37907. */
  37908. updateViewport( /*renderContext*/ ) {}
  37909. // utils
  37910. /**
  37911. * Returns `true` if the given 3D object is fully occluded by other
  37912. * 3D objects in the scene. Backends must implement this method by using
  37913. * a Occlusion Query API.
  37914. *
  37915. * @abstract
  37916. * @param {RenderContext} renderContext - The render context.
  37917. * @param {Object3D} object - The 3D object to test.
  37918. * @return {Boolean} Whether the 3D object is fully occluded or not.
  37919. */
  37920. isOccluded( /*renderContext, object*/ ) {}
  37921. /**
  37922. * Resolves the time stamp for the given render context and type.
  37923. *
  37924. * @async
  37925. * @abstract
  37926. * @param {RenderContext} renderContext - The render context.
  37927. * @param {String} type - The render context.
  37928. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  37929. */
  37930. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  37931. /**
  37932. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37933. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37934. *
  37935. * @async
  37936. * @abstract
  37937. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37938. */
  37939. async waitForGPU() {}
  37940. /**
  37941. * This method performs a readback operation by moving buffer data from
  37942. * a storage buffer attribute from the GPU to the CPU.
  37943. *
  37944. * @async
  37945. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37946. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37947. */
  37948. async getArrayBufferAsync( /* attribute */ ) {}
  37949. /**
  37950. * Checks if the given feature is supported by the backend.
  37951. *
  37952. * @async
  37953. * @abstract
  37954. * @param {String} name - The feature's name.
  37955. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37956. */
  37957. async hasFeatureAsync( /*name*/ ) { }
  37958. /**
  37959. * Checks if the given feature is supported by the backend.
  37960. *
  37961. * @abstract
  37962. * @param {String} name - The feature's name.
  37963. * @return {Boolean} Whether the feature is supported or not.
  37964. */
  37965. hasFeature( /*name*/ ) {}
  37966. /**
  37967. * Returns the maximum anisotropy texture filtering value.
  37968. *
  37969. * @abstract
  37970. * @return {Number} The maximum anisotropy texture filtering value.
  37971. */
  37972. getMaxAnisotropy() {}
  37973. /**
  37974. * Returns the drawing buffer size.
  37975. *
  37976. * @return {Vector2} The drawing buffer size.
  37977. */
  37978. getDrawingBufferSize() {
  37979. _vector2 = _vector2 || new Vector2();
  37980. return this.renderer.getDrawingBufferSize( _vector2 );
  37981. }
  37982. /**
  37983. * Defines the scissor test.
  37984. *
  37985. * @abstract
  37986. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  37987. */
  37988. setScissorTest( /*boolean*/ ) { }
  37989. /**
  37990. * Returns the clear color and alpha into a single
  37991. * color object.
  37992. *
  37993. * @return {Color4} The clear color.
  37994. */
  37995. getClearColor() {
  37996. const renderer = this.renderer;
  37997. _color4 = _color4 || new Color4();
  37998. renderer.getClearColor( _color4 );
  37999. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  38000. return _color4;
  38001. }
  38002. /**
  38003. * Returns the DOM element. If no DOM element exists, the backend
  38004. * creates a new one.
  38005. *
  38006. * @return {HTMLCanvasElement} The DOM element.
  38007. */
  38008. getDomElement() {
  38009. let domElement = this.domElement;
  38010. if ( domElement === null ) {
  38011. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38012. // OffscreenCanvas does not have setAttribute, see #22811
  38013. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38014. this.domElement = domElement;
  38015. }
  38016. return domElement;
  38017. }
  38018. /**
  38019. * Sets a dictionary for the given object into the
  38020. * internal data structure.
  38021. *
  38022. * @param {Object} object - The object.
  38023. * @param {Object} value - The dictionary to set.
  38024. */
  38025. set( object, value ) {
  38026. this.data.set( object, value );
  38027. }
  38028. /**
  38029. * Returns the dictionary for the given object.
  38030. *
  38031. * @param {Object} object - The object.
  38032. * @return {Object} The object's dictionary.
  38033. */
  38034. get( object ) {
  38035. let map = this.data.get( object );
  38036. if ( map === undefined ) {
  38037. map = {};
  38038. this.data.set( object, map );
  38039. }
  38040. return map;
  38041. }
  38042. /**
  38043. * Checks if the given object has a dictionary
  38044. * with data defined.
  38045. *
  38046. * @param {Object} object - The object.
  38047. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  38048. */
  38049. has( object ) {
  38050. return this.data.has( object );
  38051. }
  38052. /**
  38053. * Deletes an object from the internal data structure.
  38054. *
  38055. * @param {Object} object - The object to delete.
  38056. */
  38057. delete( object ) {
  38058. this.data.delete( object );
  38059. }
  38060. /**
  38061. * Frees internal resources.
  38062. *
  38063. * @abstract
  38064. */
  38065. dispose() { }
  38066. }
  38067. let _id$1 = 0;
  38068. /**
  38069. * This module is internally used in context of compute shaders.
  38070. * This type of shader is not natively supported in WebGL 2 and
  38071. * thus implemented via Transform Feedback. `DualAttributeData`
  38072. * manages the related data.
  38073. *
  38074. * @private
  38075. */
  38076. class DualAttributeData {
  38077. constructor( attributeData, dualBuffer ) {
  38078. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38079. this.type = attributeData.type;
  38080. this.bufferType = attributeData.bufferType;
  38081. this.pbo = attributeData.pbo;
  38082. this.byteLength = attributeData.byteLength;
  38083. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38084. this.version = attributeData.version;
  38085. this.isInteger = attributeData.isInteger;
  38086. this.activeBufferIndex = 0;
  38087. this.baseId = attributeData.id;
  38088. }
  38089. get id() {
  38090. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38091. }
  38092. get bufferGPU() {
  38093. return this.buffers[ this.activeBufferIndex ];
  38094. }
  38095. get transformBuffer() {
  38096. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38097. }
  38098. switchBuffers() {
  38099. this.activeBufferIndex ^= 1;
  38100. }
  38101. }
  38102. /**
  38103. * A WebGL 2 backend utility module for managing shader attributes.
  38104. *
  38105. * @private
  38106. */
  38107. class WebGLAttributeUtils {
  38108. /**
  38109. * Constructs a new utility object.
  38110. *
  38111. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38112. */
  38113. constructor( backend ) {
  38114. /**
  38115. * A reference to the WebGL 2 backend.
  38116. *
  38117. * @type {WebGLBackend}
  38118. */
  38119. this.backend = backend;
  38120. }
  38121. /**
  38122. * Creates the GPU buffer for the given buffer attribute.
  38123. *
  38124. * @param {BufferAttribute} attribute - The buffer attribute.
  38125. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38126. */
  38127. createAttribute( attribute, bufferType ) {
  38128. const backend = this.backend;
  38129. const { gl } = backend;
  38130. const array = attribute.array;
  38131. const usage = attribute.usage || gl.STATIC_DRAW;
  38132. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38133. const bufferData = backend.get( bufferAttribute );
  38134. let bufferGPU = bufferData.bufferGPU;
  38135. if ( bufferGPU === undefined ) {
  38136. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38137. bufferData.bufferGPU = bufferGPU;
  38138. bufferData.bufferType = bufferType;
  38139. bufferData.version = bufferAttribute.version;
  38140. }
  38141. //attribute.onUploadCallback();
  38142. let type;
  38143. if ( array instanceof Float32Array ) {
  38144. type = gl.FLOAT;
  38145. } else if ( array instanceof Uint16Array ) {
  38146. if ( attribute.isFloat16BufferAttribute ) {
  38147. type = gl.HALF_FLOAT;
  38148. } else {
  38149. type = gl.UNSIGNED_SHORT;
  38150. }
  38151. } else if ( array instanceof Int16Array ) {
  38152. type = gl.SHORT;
  38153. } else if ( array instanceof Uint32Array ) {
  38154. type = gl.UNSIGNED_INT;
  38155. } else if ( array instanceof Int32Array ) {
  38156. type = gl.INT;
  38157. } else if ( array instanceof Int8Array ) {
  38158. type = gl.BYTE;
  38159. } else if ( array instanceof Uint8Array ) {
  38160. type = gl.UNSIGNED_BYTE;
  38161. } else if ( array instanceof Uint8ClampedArray ) {
  38162. type = gl.UNSIGNED_BYTE;
  38163. } else {
  38164. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38165. }
  38166. let attributeData = {
  38167. bufferGPU,
  38168. bufferType,
  38169. type,
  38170. byteLength: array.byteLength,
  38171. bytesPerElement: array.BYTES_PER_ELEMENT,
  38172. version: attribute.version,
  38173. pbo: attribute.pbo,
  38174. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38175. id: _id$1 ++
  38176. };
  38177. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38178. // create buffer for transform feedback use
  38179. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38180. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38181. }
  38182. backend.set( attribute, attributeData );
  38183. }
  38184. /**
  38185. * Updates the GPU buffer of the given buffer attribute.
  38186. *
  38187. * @param {BufferAttribute} attribute - The buffer attribute.
  38188. */
  38189. updateAttribute( attribute ) {
  38190. const backend = this.backend;
  38191. const { gl } = backend;
  38192. const array = attribute.array;
  38193. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38194. const bufferData = backend.get( bufferAttribute );
  38195. const bufferType = bufferData.bufferType;
  38196. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38197. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38198. if ( updateRanges.length === 0 ) {
  38199. // Not using update ranges
  38200. gl.bufferSubData( bufferType, 0, array );
  38201. } else {
  38202. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38203. const range = updateRanges[ i ];
  38204. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38205. array, range.start, range.count );
  38206. }
  38207. bufferAttribute.clearUpdateRanges();
  38208. }
  38209. gl.bindBuffer( bufferType, null );
  38210. bufferData.version = bufferAttribute.version;
  38211. }
  38212. /**
  38213. * Destroys the GPU buffer of the given buffer attribute.
  38214. *
  38215. * @param {BufferAttribute} attribute - The buffer attribute.
  38216. */
  38217. destroyAttribute( attribute ) {
  38218. const backend = this.backend;
  38219. const { gl } = backend;
  38220. if ( attribute.isInterleavedBufferAttribute ) {
  38221. backend.delete( attribute.data );
  38222. }
  38223. const attributeData = backend.get( attribute );
  38224. gl.deleteBuffer( attributeData.bufferGPU );
  38225. backend.delete( attribute );
  38226. }
  38227. /**
  38228. * This method performs a readback operation by moving buffer data from
  38229. * a storage buffer attribute from the GPU to the CPU.
  38230. *
  38231. * @async
  38232. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38233. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38234. */
  38235. async getArrayBufferAsync( attribute ) {
  38236. const backend = this.backend;
  38237. const { gl } = backend;
  38238. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38239. const { bufferGPU } = backend.get( bufferAttribute );
  38240. const array = attribute.array;
  38241. const byteLength = array.byteLength;
  38242. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38243. const writeBuffer = gl.createBuffer();
  38244. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38245. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38246. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38247. await backend.utils._clientWaitAsync();
  38248. const dstBuffer = new attribute.array.constructor( array.length );
  38249. // Ensure the buffer is bound before reading
  38250. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38251. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38252. gl.deleteBuffer( writeBuffer );
  38253. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38254. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38255. return dstBuffer.buffer;
  38256. }
  38257. /**
  38258. * Creates a WebGL buffer with the given data.
  38259. *
  38260. * @private
  38261. * @param {WebGL2RenderingContext} gl - The rendering context.
  38262. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38263. * @param {TypedArray} array - The array of the buffer attribute.
  38264. * @param {GLenum} usage - The usage.
  38265. * @return {WebGLBuffer} The WebGL buffer.
  38266. */
  38267. _createBuffer( gl, bufferType, array, usage ) {
  38268. const bufferGPU = gl.createBuffer();
  38269. gl.bindBuffer( bufferType, bufferGPU );
  38270. gl.bufferData( bufferType, array, usage );
  38271. gl.bindBuffer( bufferType, null );
  38272. return bufferGPU;
  38273. }
  38274. }
  38275. let initialized$1 = false, equationToGL, factorToGL;
  38276. /**
  38277. * A WebGL 2 backend utility module for managing the WebGL state.
  38278. *
  38279. * The major goal of this module is to reduce the number of state changes
  38280. * by caching the WEbGL state with a series of variables. In this way, the
  38281. * renderer only executes state change commands when necessary which
  38282. * improves the overall performance.
  38283. *
  38284. * @private
  38285. */
  38286. class WebGLState {
  38287. /**
  38288. * Constructs a new utility object.
  38289. *
  38290. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38291. */
  38292. constructor( backend ) {
  38293. /**
  38294. * A reference to the WebGL 2 backend.
  38295. *
  38296. * @type {WebGLBackend}
  38297. */
  38298. this.backend = backend;
  38299. /**
  38300. * A reference to the rendering context.
  38301. *
  38302. * @type {WebGL2RenderingContext}
  38303. */
  38304. this.gl = this.backend.gl;
  38305. // Below properties are intended to cache
  38306. // the WebGL state and are not explicitly
  38307. // documented for convenience reasons.
  38308. this.enabled = {};
  38309. this.currentFlipSided = null;
  38310. this.currentCullFace = null;
  38311. this.currentProgram = null;
  38312. this.currentBlendingEnabled = false;
  38313. this.currentBlending = null;
  38314. this.currentBlendSrc = null;
  38315. this.currentBlendDst = null;
  38316. this.currentBlendSrcAlpha = null;
  38317. this.currentBlendDstAlpha = null;
  38318. this.currentPremultipledAlpha = null;
  38319. this.currentPolygonOffsetFactor = null;
  38320. this.currentPolygonOffsetUnits = null;
  38321. this.currentColorMask = null;
  38322. this.currentDepthFunc = null;
  38323. this.currentDepthMask = null;
  38324. this.currentStencilFunc = null;
  38325. this.currentStencilRef = null;
  38326. this.currentStencilFuncMask = null;
  38327. this.currentStencilFail = null;
  38328. this.currentStencilZFail = null;
  38329. this.currentStencilZPass = null;
  38330. this.currentStencilMask = null;
  38331. this.currentLineWidth = null;
  38332. this.currentClippingPlanes = 0;
  38333. this.currentBoundFramebuffers = {};
  38334. this.currentDrawbuffers = new WeakMap();
  38335. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38336. this.currentTextureSlot = null;
  38337. this.currentBoundTextures = {};
  38338. this.currentBoundBufferBases = {};
  38339. if ( initialized$1 === false ) {
  38340. this._init();
  38341. initialized$1 = true;
  38342. }
  38343. }
  38344. /**
  38345. * Inits the state of the utility.
  38346. *
  38347. * @private
  38348. */
  38349. _init() {
  38350. const gl = this.gl;
  38351. // Store only WebGL constants here.
  38352. equationToGL = {
  38353. [ AddEquation ]: gl.FUNC_ADD,
  38354. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38355. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38356. };
  38357. factorToGL = {
  38358. [ ZeroFactor ]: gl.ZERO,
  38359. [ OneFactor ]: gl.ONE,
  38360. [ SrcColorFactor ]: gl.SRC_COLOR,
  38361. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38362. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38363. [ DstColorFactor ]: gl.DST_COLOR,
  38364. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38365. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38366. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38367. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38368. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38369. };
  38370. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38371. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38372. this.currentScissor = new Vector4().fromArray( scissorParam );
  38373. this.currentViewport = new Vector4().fromArray( viewportParam );
  38374. this._tempVec4 = new Vector4();
  38375. }
  38376. /**
  38377. * Enables the given WebGL capability.
  38378. *
  38379. * This method caches the capability state so
  38380. * `gl.enable()` is only called when necessary.
  38381. *
  38382. * @param {GLenum} id - The capability to enable.
  38383. */
  38384. enable( id ) {
  38385. const { enabled } = this;
  38386. if ( enabled[ id ] !== true ) {
  38387. this.gl.enable( id );
  38388. enabled[ id ] = true;
  38389. }
  38390. }
  38391. /**
  38392. * Disables the given WebGL capability.
  38393. *
  38394. * This method caches the capability state so
  38395. * `gl.disable()` is only called when necessary.
  38396. *
  38397. * @param {GLenum} id - The capability to enable.
  38398. */
  38399. disable( id ) {
  38400. const { enabled } = this;
  38401. if ( enabled[ id ] !== false ) {
  38402. this.gl.disable( id );
  38403. enabled[ id ] = false;
  38404. }
  38405. }
  38406. /**
  38407. * Specifies whether polygons are front- or back-facing
  38408. * by setting the winding orientation.
  38409. *
  38410. * This method caches the state so `gl.frontFace()` is only
  38411. * called when necessary.
  38412. *
  38413. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  38414. */
  38415. setFlipSided( flipSided ) {
  38416. if ( this.currentFlipSided !== flipSided ) {
  38417. const { gl } = this;
  38418. if ( flipSided ) {
  38419. gl.frontFace( gl.CW );
  38420. } else {
  38421. gl.frontFace( gl.CCW );
  38422. }
  38423. this.currentFlipSided = flipSided;
  38424. }
  38425. }
  38426. /**
  38427. * Specifies whether or not front- and/or back-facing
  38428. * polygons can be culled.
  38429. *
  38430. * This method caches the state so `gl.cullFace()` is only
  38431. * called when necessary.
  38432. *
  38433. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  38434. */
  38435. setCullFace( cullFace ) {
  38436. const { gl } = this;
  38437. if ( cullFace !== CullFaceNone ) {
  38438. this.enable( gl.CULL_FACE );
  38439. if ( cullFace !== this.currentCullFace ) {
  38440. if ( cullFace === CullFaceBack ) {
  38441. gl.cullFace( gl.BACK );
  38442. } else if ( cullFace === CullFaceFront ) {
  38443. gl.cullFace( gl.FRONT );
  38444. } else {
  38445. gl.cullFace( gl.FRONT_AND_BACK );
  38446. }
  38447. }
  38448. } else {
  38449. this.disable( gl.CULL_FACE );
  38450. }
  38451. this.currentCullFace = cullFace;
  38452. }
  38453. /**
  38454. * Specifies the width of line primitives.
  38455. *
  38456. * This method caches the state so `gl.lineWidth()` is only
  38457. * called when necessary.
  38458. *
  38459. * @param {Number} width - The line width.
  38460. */
  38461. setLineWidth( width ) {
  38462. const { currentLineWidth, gl } = this;
  38463. if ( width !== currentLineWidth ) {
  38464. gl.lineWidth( width );
  38465. this.currentLineWidth = width;
  38466. }
  38467. }
  38468. /**
  38469. * Defines the blending.
  38470. *
  38471. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  38472. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  38473. *
  38474. * @param {Number} blending - The blending type.
  38475. * @param {Number} blendEquation - The blending equation.
  38476. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  38477. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  38478. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  38479. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  38480. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  38481. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  38482. */
  38483. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38484. const { gl } = this;
  38485. if ( blending === NoBlending ) {
  38486. if ( this.currentBlendingEnabled === true ) {
  38487. this.disable( gl.BLEND );
  38488. this.currentBlendingEnabled = false;
  38489. }
  38490. return;
  38491. }
  38492. if ( this.currentBlendingEnabled === false ) {
  38493. this.enable( gl.BLEND );
  38494. this.currentBlendingEnabled = true;
  38495. }
  38496. if ( blending !== CustomBlending ) {
  38497. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38498. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38499. gl.blendEquation( gl.FUNC_ADD );
  38500. this.currentBlendEquation = AddEquation;
  38501. this.currentBlendEquationAlpha = AddEquation;
  38502. }
  38503. if ( premultipliedAlpha ) {
  38504. switch ( blending ) {
  38505. case NormalBlending:
  38506. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38507. break;
  38508. case AdditiveBlending:
  38509. gl.blendFunc( gl.ONE, gl.ONE );
  38510. break;
  38511. case SubtractiveBlending:
  38512. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38513. break;
  38514. case MultiplyBlending:
  38515. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38516. break;
  38517. default:
  38518. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38519. break;
  38520. }
  38521. } else {
  38522. switch ( blending ) {
  38523. case NormalBlending:
  38524. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38525. break;
  38526. case AdditiveBlending:
  38527. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38528. break;
  38529. case SubtractiveBlending:
  38530. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38531. break;
  38532. case MultiplyBlending:
  38533. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38534. break;
  38535. default:
  38536. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38537. break;
  38538. }
  38539. }
  38540. this.currentBlendSrc = null;
  38541. this.currentBlendDst = null;
  38542. this.currentBlendSrcAlpha = null;
  38543. this.currentBlendDstAlpha = null;
  38544. this.currentBlending = blending;
  38545. this.currentPremultipledAlpha = premultipliedAlpha;
  38546. }
  38547. return;
  38548. }
  38549. // custom blending
  38550. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38551. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38552. blendDstAlpha = blendDstAlpha || blendDst;
  38553. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38554. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38555. this.currentBlendEquation = blendEquation;
  38556. this.currentBlendEquationAlpha = blendEquationAlpha;
  38557. }
  38558. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38559. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38560. this.currentBlendSrc = blendSrc;
  38561. this.currentBlendDst = blendDst;
  38562. this.currentBlendSrcAlpha = blendSrcAlpha;
  38563. this.currentBlendDstAlpha = blendDstAlpha;
  38564. }
  38565. this.currentBlending = blending;
  38566. this.currentPremultipledAlpha = false;
  38567. }
  38568. /**
  38569. * Specifies whether colors can be written when rendering
  38570. * into a framebuffer or not.
  38571. *
  38572. * This method caches the state so `gl.colorMask()` is only
  38573. * called when necessary.
  38574. *
  38575. * @param {Boolean} colorMask - The color mask.
  38576. */
  38577. setColorMask( colorMask ) {
  38578. if ( this.currentColorMask !== colorMask ) {
  38579. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38580. this.currentColorMask = colorMask;
  38581. }
  38582. }
  38583. /**
  38584. * Specifies whether the depth test is enabled or not.
  38585. *
  38586. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  38587. */
  38588. setDepthTest( depthTest ) {
  38589. const { gl } = this;
  38590. if ( depthTest ) {
  38591. this.enable( gl.DEPTH_TEST );
  38592. } else {
  38593. this.disable( gl.DEPTH_TEST );
  38594. }
  38595. }
  38596. /**
  38597. * Specifies whether depth values can be written when rendering
  38598. * into a framebuffer or not.
  38599. *
  38600. * This method caches the state so `gl.depthMask()` is only
  38601. * called when necessary.
  38602. *
  38603. * @param {Boolean} depthMask - The depth mask.
  38604. */
  38605. setDepthMask( depthMask ) {
  38606. if ( this.currentDepthMask !== depthMask ) {
  38607. this.gl.depthMask( depthMask );
  38608. this.currentDepthMask = depthMask;
  38609. }
  38610. }
  38611. /**
  38612. * Specifies the depth compare function.
  38613. *
  38614. * This method caches the state so `gl.depthFunc()` is only
  38615. * called when necessary.
  38616. *
  38617. * @param {Number} depthFunc - The depth compare function.
  38618. */
  38619. setDepthFunc( depthFunc ) {
  38620. if ( this.currentDepthFunc !== depthFunc ) {
  38621. const { gl } = this;
  38622. switch ( depthFunc ) {
  38623. case NeverDepth:
  38624. gl.depthFunc( gl.NEVER );
  38625. break;
  38626. case AlwaysDepth:
  38627. gl.depthFunc( gl.ALWAYS );
  38628. break;
  38629. case LessDepth:
  38630. gl.depthFunc( gl.LESS );
  38631. break;
  38632. case LessEqualDepth:
  38633. gl.depthFunc( gl.LEQUAL );
  38634. break;
  38635. case EqualDepth:
  38636. gl.depthFunc( gl.EQUAL );
  38637. break;
  38638. case GreaterEqualDepth:
  38639. gl.depthFunc( gl.GEQUAL );
  38640. break;
  38641. case GreaterDepth:
  38642. gl.depthFunc( gl.GREATER );
  38643. break;
  38644. case NotEqualDepth:
  38645. gl.depthFunc( gl.NOTEQUAL );
  38646. break;
  38647. default:
  38648. gl.depthFunc( gl.LEQUAL );
  38649. }
  38650. this.currentDepthFunc = depthFunc;
  38651. }
  38652. }
  38653. /**
  38654. * Specifies the viewport.
  38655. *
  38656. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38657. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38658. * @param {Number} width - The width of the viewport.
  38659. * @param {Number} height - The height of the viewport.
  38660. *
  38661. */
  38662. scissor( x, y, width, height ) {
  38663. const scissor = this._tempVec4.set( x, y, width, height );
  38664. if ( this.currentScissor.equals( scissor ) === false ) {
  38665. const { gl } = this;
  38666. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  38667. this.currentScissor.copy( scissor );
  38668. }
  38669. }
  38670. /**
  38671. * Specifies the viewport.
  38672. *
  38673. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38674. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38675. * @param {Number} width - The width of the viewport.
  38676. * @param {Number} height - The height of the viewport.
  38677. *
  38678. */
  38679. viewport( x, y, width, height ) {
  38680. const viewport = this._tempVec4.set( x, y, width, height );
  38681. if ( this.currentViewport.equals( viewport ) === false ) {
  38682. const { gl } = this;
  38683. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  38684. this.currentViewport.copy( viewport );
  38685. }
  38686. }
  38687. /**
  38688. * Defines the scissor test.
  38689. *
  38690. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38691. */
  38692. setScissorTest( boolean ) {
  38693. const gl = this.gl;
  38694. if ( boolean ) {
  38695. gl.enable( gl.SCISSOR_TEST );
  38696. } else {
  38697. gl.disable( gl.SCISSOR_TEST );
  38698. }
  38699. }
  38700. /**
  38701. * Specifies whether the stencil test is enabled or not.
  38702. *
  38703. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  38704. */
  38705. setStencilTest( stencilTest ) {
  38706. const { gl } = this;
  38707. if ( stencilTest ) {
  38708. this.enable( gl.STENCIL_TEST );
  38709. } else {
  38710. this.disable( gl.STENCIL_TEST );
  38711. }
  38712. }
  38713. /**
  38714. * Specifies whether stencil values can be written when rendering
  38715. * into a framebuffer or not.
  38716. *
  38717. * This method caches the state so `gl.stencilMask()` is only
  38718. * called when necessary.
  38719. *
  38720. * @param {Boolean} stencilMask - The stencil mask.
  38721. */
  38722. setStencilMask( stencilMask ) {
  38723. if ( this.currentStencilMask !== stencilMask ) {
  38724. this.gl.stencilMask( stencilMask );
  38725. this.currentStencilMask = stencilMask;
  38726. }
  38727. }
  38728. /**
  38729. * Specifies whether the stencil test functions.
  38730. *
  38731. * This method caches the state so `gl.stencilFunc()` is only
  38732. * called when necessary.
  38733. *
  38734. * @param {Number} stencilFunc - The stencil compare function.
  38735. * @param {Number} stencilRef - The reference value for the stencil test.
  38736. * @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.
  38737. */
  38738. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  38739. if ( this.currentStencilFunc !== stencilFunc ||
  38740. this.currentStencilRef !== stencilRef ||
  38741. this.currentStencilFuncMask !== stencilMask ) {
  38742. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  38743. this.currentStencilFunc = stencilFunc;
  38744. this.currentStencilRef = stencilRef;
  38745. this.currentStencilFuncMask = stencilMask;
  38746. }
  38747. }
  38748. /**
  38749. * Specifies whether the stencil test operation.
  38750. *
  38751. * This method caches the state so `gl.stencilOp()` is only
  38752. * called when necessary.
  38753. *
  38754. * @param {Number} stencilFail - The function to use when the stencil test fails.
  38755. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  38756. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  38757. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  38758. */
  38759. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  38760. if ( this.currentStencilFail !== stencilFail ||
  38761. this.currentStencilZFail !== stencilZFail ||
  38762. this.currentStencilZPass !== stencilZPass ) {
  38763. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  38764. this.currentStencilFail = stencilFail;
  38765. this.currentStencilZFail = stencilZFail;
  38766. this.currentStencilZPass = stencilZPass;
  38767. }
  38768. }
  38769. /**
  38770. * Configures the WebGL state for the given material.
  38771. *
  38772. * @param {Material} material - The material to configure the state for.
  38773. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  38774. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  38775. */
  38776. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  38777. const { gl } = this;
  38778. material.side === DoubleSide
  38779. ? this.disable( gl.CULL_FACE )
  38780. : this.enable( gl.CULL_FACE );
  38781. let flipSided = ( material.side === BackSide );
  38782. if ( frontFaceCW ) flipSided = ! flipSided;
  38783. this.setFlipSided( flipSided );
  38784. ( material.blending === NormalBlending && material.transparent === false )
  38785. ? this.setBlending( NoBlending )
  38786. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  38787. this.setDepthFunc( material.depthFunc );
  38788. this.setDepthTest( material.depthTest );
  38789. this.setDepthMask( material.depthWrite );
  38790. this.setColorMask( material.colorWrite );
  38791. const stencilWrite = material.stencilWrite;
  38792. this.setStencilTest( stencilWrite );
  38793. if ( stencilWrite ) {
  38794. this.setStencilMask( material.stencilWriteMask );
  38795. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  38796. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  38797. }
  38798. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  38799. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  38800. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  38801. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  38802. if ( hardwareClippingPlanes > 0 ) {
  38803. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  38804. const CLIP_DISTANCE0_WEBGL = 0x3000;
  38805. for ( let i = 0; i < 8; i ++ ) {
  38806. if ( i < hardwareClippingPlanes ) {
  38807. this.enable( CLIP_DISTANCE0_WEBGL + i );
  38808. } else {
  38809. this.disable( CLIP_DISTANCE0_WEBGL + i );
  38810. }
  38811. }
  38812. }
  38813. }
  38814. }
  38815. /**
  38816. * Specifies the polygon offset.
  38817. *
  38818. * This method caches the state so `gl.polygonOffset()` is only
  38819. * called when necessary.
  38820. *
  38821. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  38822. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  38823. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  38824. */
  38825. setPolygonOffset( polygonOffset, factor, units ) {
  38826. const { gl } = this;
  38827. if ( polygonOffset ) {
  38828. this.enable( gl.POLYGON_OFFSET_FILL );
  38829. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  38830. gl.polygonOffset( factor, units );
  38831. this.currentPolygonOffsetFactor = factor;
  38832. this.currentPolygonOffsetUnits = units;
  38833. }
  38834. } else {
  38835. this.disable( gl.POLYGON_OFFSET_FILL );
  38836. }
  38837. }
  38838. /**
  38839. * Defines the usage of the given WebGL program.
  38840. *
  38841. * This method caches the state so `gl.useProgram()` is only
  38842. * called when necessary.
  38843. *
  38844. * @param {WebGLProgram} program - The WebGL program to use.
  38845. * @return {Boolean} Whether a program change has been executed or not.
  38846. */
  38847. useProgram( program ) {
  38848. if ( this.currentProgram !== program ) {
  38849. this.gl.useProgram( program );
  38850. this.currentProgram = program;
  38851. return true;
  38852. }
  38853. return false;
  38854. }
  38855. // framebuffer
  38856. /**
  38857. * Binds the given framebuffer.
  38858. *
  38859. * This method caches the state so `gl.bindFramebuffer()` is only
  38860. * called when necessary.
  38861. *
  38862. * @param {Number} target - The binding point (target).
  38863. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  38864. * @return {Boolean} Whether a bind has been executed or not.
  38865. */
  38866. bindFramebuffer( target, framebuffer ) {
  38867. const { gl, currentBoundFramebuffers } = this;
  38868. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  38869. gl.bindFramebuffer( target, framebuffer );
  38870. currentBoundFramebuffers[ target ] = framebuffer;
  38871. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  38872. if ( target === gl.DRAW_FRAMEBUFFER ) {
  38873. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  38874. }
  38875. if ( target === gl.FRAMEBUFFER ) {
  38876. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  38877. }
  38878. return true;
  38879. }
  38880. return false;
  38881. }
  38882. /**
  38883. * Defines draw buffers to which fragment colors are written into.
  38884. * Configures the MRT setup of custom framebuffers.
  38885. *
  38886. * This method caches the state so `gl.drawBuffers()` is only
  38887. * called when necessary.
  38888. *
  38889. * @param {RenderContext} renderContext - The render context.
  38890. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  38891. */
  38892. drawBuffers( renderContext, framebuffer ) {
  38893. const { gl } = this;
  38894. let drawBuffers = [];
  38895. let needsUpdate = false;
  38896. if ( renderContext.textures !== null ) {
  38897. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  38898. if ( drawBuffers === undefined ) {
  38899. drawBuffers = [];
  38900. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  38901. }
  38902. const textures = renderContext.textures;
  38903. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  38904. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  38905. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  38906. }
  38907. drawBuffers.length = textures.length;
  38908. needsUpdate = true;
  38909. }
  38910. } else {
  38911. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  38912. drawBuffers[ 0 ] = gl.BACK;
  38913. needsUpdate = true;
  38914. }
  38915. }
  38916. if ( needsUpdate ) {
  38917. gl.drawBuffers( drawBuffers );
  38918. }
  38919. }
  38920. // texture
  38921. /**
  38922. * Makes the given texture unit active.
  38923. *
  38924. * This method caches the state so `gl.activeTexture()` is only
  38925. * called when necessary.
  38926. *
  38927. * @param {Number} webglSlot - The texture unit to make active.
  38928. */
  38929. activeTexture( webglSlot ) {
  38930. const { gl, currentTextureSlot, maxTextures } = this;
  38931. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38932. if ( currentTextureSlot !== webglSlot ) {
  38933. gl.activeTexture( webglSlot );
  38934. this.currentTextureSlot = webglSlot;
  38935. }
  38936. }
  38937. /**
  38938. * Binds the given WebGL texture to a target.
  38939. *
  38940. * This method caches the state so `gl.bindTexture()` is only
  38941. * called when necessary.
  38942. *
  38943. * @param {Number} webglType - The binding point (target).
  38944. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  38945. * @param {Number} webglSlot - The texture.
  38946. */
  38947. bindTexture( webglType, webglTexture, webglSlot ) {
  38948. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  38949. if ( webglSlot === undefined ) {
  38950. if ( currentTextureSlot === null ) {
  38951. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38952. } else {
  38953. webglSlot = currentTextureSlot;
  38954. }
  38955. }
  38956. let boundTexture = currentBoundTextures[ webglSlot ];
  38957. if ( boundTexture === undefined ) {
  38958. boundTexture = { type: undefined, texture: undefined };
  38959. currentBoundTextures[ webglSlot ] = boundTexture;
  38960. }
  38961. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  38962. if ( currentTextureSlot !== webglSlot ) {
  38963. gl.activeTexture( webglSlot );
  38964. this.currentTextureSlot = webglSlot;
  38965. }
  38966. gl.bindTexture( webglType, webglTexture );
  38967. boundTexture.type = webglType;
  38968. boundTexture.texture = webglTexture;
  38969. }
  38970. }
  38971. /**
  38972. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  38973. *
  38974. * This method caches the state so `gl.bindBufferBase()` is only
  38975. * called when necessary.
  38976. *
  38977. * @param {Number} target - The target for the bind operation.
  38978. * @param {Number} index - The index of the target.
  38979. * @param {WebGLBuffer} buffer - The WebGL buffer.
  38980. * @return {Boolean} Whether a bind has been executed or not.
  38981. */
  38982. bindBufferBase( target, index, buffer ) {
  38983. const { gl } = this;
  38984. const key = `${target}-${index}`;
  38985. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  38986. gl.bindBufferBase( target, index, buffer );
  38987. this.currentBoundBufferBases[ key ] = buffer;
  38988. return true;
  38989. }
  38990. return false;
  38991. }
  38992. /**
  38993. * Unbinds the current bound texture.
  38994. *
  38995. * This method caches the state so `gl.bindTexture()` is only
  38996. * called when necessary.
  38997. */
  38998. unbindTexture() {
  38999. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39000. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39001. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39002. gl.bindTexture( boundTexture.type, null );
  39003. boundTexture.type = undefined;
  39004. boundTexture.texture = undefined;
  39005. }
  39006. }
  39007. }
  39008. /**
  39009. * A WebGL 2 backend utility module with common helpers.
  39010. *
  39011. * @private
  39012. */
  39013. class WebGLUtils {
  39014. /**
  39015. * Constructs a new utility object.
  39016. *
  39017. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39018. */
  39019. constructor( backend ) {
  39020. /**
  39021. * A reference to the WebGL 2 backend.
  39022. *
  39023. * @type {WebGLBackend}
  39024. */
  39025. this.backend = backend;
  39026. /**
  39027. * A reference to the rendering context.
  39028. *
  39029. * @type {WebGL2RenderingContext}
  39030. */
  39031. this.gl = this.backend.gl;
  39032. /**
  39033. * A reference to a backend module holding extension-related
  39034. * utility functions.
  39035. *
  39036. * @type {WebGLExtensions}
  39037. */
  39038. this.extensions = backend.extensions;
  39039. }
  39040. /**
  39041. * Converts the given three.js constant into a WebGL constant.
  39042. * The method currently supports the conversion of texture formats
  39043. * and types.
  39044. *
  39045. * @param {Number} p - The three.js constant.
  39046. * @param {String} [colorSpace=NoColorSpace] - The color space.
  39047. * @return {Number} The corresponding WebGL constant.
  39048. */
  39049. convert( p, colorSpace = NoColorSpace ) {
  39050. const { gl, extensions } = this;
  39051. let extension;
  39052. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39053. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39054. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39055. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39056. if ( p === ByteType ) return gl.BYTE;
  39057. if ( p === ShortType ) return gl.SHORT;
  39058. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39059. if ( p === IntType ) return gl.INT;
  39060. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39061. if ( p === FloatType ) return gl.FLOAT;
  39062. if ( p === HalfFloatType ) {
  39063. return gl.HALF_FLOAT;
  39064. }
  39065. if ( p === AlphaFormat ) return gl.ALPHA;
  39066. if ( p === RGBFormat ) return gl.RGB;
  39067. if ( p === RGBAFormat ) return gl.RGBA;
  39068. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39069. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39070. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39071. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39072. // WebGL2 formats.
  39073. if ( p === RedFormat ) return gl.RED;
  39074. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39075. if ( p === RGFormat ) return gl.RG;
  39076. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39077. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39078. // S3TC
  39079. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39080. if ( colorSpace === SRGBColorSpace ) {
  39081. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39082. if ( extension !== null ) {
  39083. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39084. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39085. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39086. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39087. } else {
  39088. return null;
  39089. }
  39090. } else {
  39091. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39092. if ( extension !== null ) {
  39093. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39094. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39095. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39096. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39097. } else {
  39098. return null;
  39099. }
  39100. }
  39101. }
  39102. // PVRTC
  39103. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39104. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39105. if ( extension !== null ) {
  39106. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39107. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39108. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39109. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39110. } else {
  39111. return null;
  39112. }
  39113. }
  39114. // ETC
  39115. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39116. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39117. if ( extension !== null ) {
  39118. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39119. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39120. } else {
  39121. return null;
  39122. }
  39123. }
  39124. // ASTC
  39125. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39126. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39127. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39128. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39129. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39130. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39131. if ( extension !== null ) {
  39132. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39133. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39134. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39135. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39136. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39137. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39138. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39139. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39140. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39141. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39142. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39143. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39144. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39145. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39146. } else {
  39147. return null;
  39148. }
  39149. }
  39150. // BPTC
  39151. if ( p === RGBA_BPTC_Format ) {
  39152. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39153. if ( extension !== null ) {
  39154. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39155. } else {
  39156. return null;
  39157. }
  39158. }
  39159. // RGTC
  39160. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39161. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39162. if ( extension !== null ) {
  39163. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39164. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39165. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39166. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39167. } else {
  39168. return null;
  39169. }
  39170. }
  39171. //
  39172. if ( p === UnsignedInt248Type ) {
  39173. return gl.UNSIGNED_INT_24_8;
  39174. }
  39175. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39176. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39177. }
  39178. /**
  39179. * This method can be used to synchronize the CPU with the GPU by waiting until
  39180. * ongoing GPU commands have been completed.
  39181. *
  39182. * @private
  39183. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39184. */
  39185. _clientWaitAsync() {
  39186. const { gl } = this;
  39187. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39188. gl.flush();
  39189. return new Promise( ( resolve, reject ) => {
  39190. function test() {
  39191. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39192. if ( res === gl.WAIT_FAILED ) {
  39193. gl.deleteSync( sync );
  39194. reject();
  39195. return;
  39196. }
  39197. if ( res === gl.TIMEOUT_EXPIRED ) {
  39198. requestAnimationFrame( test );
  39199. return;
  39200. }
  39201. gl.deleteSync( sync );
  39202. resolve();
  39203. }
  39204. test();
  39205. } );
  39206. }
  39207. }
  39208. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39209. /**
  39210. * A WebGL 2 backend utility module for managing textures.
  39211. *
  39212. * @private
  39213. */
  39214. class WebGLTextureUtils {
  39215. /**
  39216. * Constructs a new utility object.
  39217. *
  39218. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39219. */
  39220. constructor( backend ) {
  39221. /**
  39222. * A reference to the WebGL 2 backend.
  39223. *
  39224. * @type {WebGLBackend}
  39225. */
  39226. this.backend = backend;
  39227. /**
  39228. * A reference to the rendering context.
  39229. *
  39230. * @type {WebGL2RenderingContext}
  39231. */
  39232. this.gl = backend.gl;
  39233. /**
  39234. * A reference to a backend module holding extension-related
  39235. * utility functions.
  39236. *
  39237. * @type {WebGLExtensions}
  39238. */
  39239. this.extensions = backend.extensions;
  39240. /**
  39241. * A dictionary for managing default textures. The key
  39242. * is the binding point (target), the value the WEbGL texture object.
  39243. *
  39244. * @type {Object<GLenum,WebGLTexture>}
  39245. */
  39246. this.defaultTextures = {};
  39247. if ( initialized === false ) {
  39248. this._init();
  39249. initialized = true;
  39250. }
  39251. }
  39252. /**
  39253. * Inits the state of the utility.
  39254. *
  39255. * @private
  39256. */
  39257. _init() {
  39258. const gl = this.gl;
  39259. // Store only WebGL constants here.
  39260. wrappingToGL = {
  39261. [ RepeatWrapping ]: gl.REPEAT,
  39262. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39263. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39264. };
  39265. filterToGL = {
  39266. [ NearestFilter ]: gl.NEAREST,
  39267. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39268. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39269. [ LinearFilter ]: gl.LINEAR,
  39270. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39271. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39272. };
  39273. compareToGL = {
  39274. [ NeverCompare ]: gl.NEVER,
  39275. [ AlwaysCompare ]: gl.ALWAYS,
  39276. [ LessCompare ]: gl.LESS,
  39277. [ LessEqualCompare ]: gl.LEQUAL,
  39278. [ EqualCompare ]: gl.EQUAL,
  39279. [ GreaterEqualCompare ]: gl.GEQUAL,
  39280. [ GreaterCompare ]: gl.GREATER,
  39281. [ NotEqualCompare ]: gl.NOTEQUAL
  39282. };
  39283. }
  39284. /**
  39285. * Returns the native texture type for the given texture.
  39286. *
  39287. * @param {Texture} texture - The texture.
  39288. * @return {GLenum} The native texture type.
  39289. */
  39290. getGLTextureType( texture ) {
  39291. const { gl } = this;
  39292. let glTextureType;
  39293. if ( texture.isCubeTexture === true ) {
  39294. glTextureType = gl.TEXTURE_CUBE_MAP;
  39295. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39296. glTextureType = gl.TEXTURE_2D_ARRAY;
  39297. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39298. glTextureType = gl.TEXTURE_3D;
  39299. } else {
  39300. glTextureType = gl.TEXTURE_2D;
  39301. }
  39302. return glTextureType;
  39303. }
  39304. /**
  39305. * Returns the native texture type for the given texture.
  39306. *
  39307. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39308. * @param {GLenum} glFormat - The WebGL format.
  39309. * @param {GLenum} glType - The WebGL type.
  39310. * @param {String} colorSpace - The texture's color space.
  39311. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39312. * @return {GLenum} The internal format.
  39313. */
  39314. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39315. const { gl, extensions } = this;
  39316. if ( internalFormatName !== null ) {
  39317. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39318. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39319. }
  39320. let internalFormat = glFormat;
  39321. if ( glFormat === gl.RED ) {
  39322. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39323. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39324. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39327. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39328. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39329. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39330. }
  39331. if ( glFormat === gl.RED_INTEGER ) {
  39332. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39333. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39334. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39335. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39336. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39337. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39338. }
  39339. if ( glFormat === gl.RG ) {
  39340. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39341. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39342. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39343. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39344. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39345. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39346. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39347. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39348. }
  39349. if ( glFormat === gl.RG_INTEGER ) {
  39350. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39351. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39352. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39353. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39354. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39355. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39356. }
  39357. if ( glFormat === gl.RGB ) {
  39358. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39359. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39360. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39361. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39362. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39363. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39364. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39365. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39366. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39367. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39368. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39369. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39370. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39371. }
  39372. if ( glFormat === gl.RGB_INTEGER ) {
  39373. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39374. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39375. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39376. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39377. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39378. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39379. }
  39380. if ( glFormat === gl.RGBA ) {
  39381. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39382. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39383. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39384. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39385. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39386. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39387. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39388. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39389. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39390. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39391. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39392. }
  39393. if ( glFormat === gl.RGBA_INTEGER ) {
  39394. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39395. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39396. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39397. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39398. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39399. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39400. }
  39401. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39402. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39403. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39404. }
  39405. if ( glFormat === gl.DEPTH_STENCIL ) {
  39406. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39407. }
  39408. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39409. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39410. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39411. extensions.get( 'EXT_color_buffer_float' );
  39412. }
  39413. return internalFormat;
  39414. }
  39415. /**
  39416. * Sets the texture parameters for the given texture.
  39417. *
  39418. * @param {GLenum} textureType - The texture type.
  39419. * @param {Texture} texture - The texture.
  39420. */
  39421. setTextureParameters( textureType, texture ) {
  39422. const { gl, extensions, backend } = this;
  39423. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39424. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39425. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39426. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39427. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39428. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39429. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39430. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39431. }
  39432. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39433. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  39434. // follow WebGPU backend mapping for texture filtering
  39435. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  39436. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39437. if ( texture.compareFunction ) {
  39438. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39439. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39440. }
  39441. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39442. if ( texture.magFilter === NearestFilter ) return;
  39443. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39444. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39445. if ( texture.anisotropy > 1 ) {
  39446. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39447. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39448. }
  39449. }
  39450. }
  39451. /**
  39452. * Creates a default texture for the given texture that can be used
  39453. * as a placeholder until the actual texture is ready for usage.
  39454. *
  39455. * @param {Texture} texture - The texture to create a default texture for.
  39456. */
  39457. createDefaultTexture( texture ) {
  39458. const { gl, backend, defaultTextures } = this;
  39459. const glTextureType = this.getGLTextureType( texture );
  39460. let textureGPU = defaultTextures[ glTextureType ];
  39461. if ( textureGPU === undefined ) {
  39462. textureGPU = gl.createTexture();
  39463. backend.state.bindTexture( glTextureType, textureGPU );
  39464. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39465. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39466. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39467. defaultTextures[ glTextureType ] = textureGPU;
  39468. }
  39469. backend.set( texture, {
  39470. textureGPU,
  39471. glTextureType,
  39472. isDefault: true
  39473. } );
  39474. }
  39475. /**
  39476. * Defines a texture on the GPU for the given texture object.
  39477. *
  39478. * @param {Texture} texture - The texture.
  39479. * @param {Object} [options={}] - Optional configuration parameter.
  39480. * @return {undefined}
  39481. */
  39482. createTexture( texture, options ) {
  39483. const { gl, backend } = this;
  39484. const { levels, width, height, depth } = options;
  39485. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39486. const glType = backend.utils.convert( texture.type );
  39487. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39488. const textureGPU = gl.createTexture();
  39489. const glTextureType = this.getGLTextureType( texture );
  39490. backend.state.bindTexture( glTextureType, textureGPU );
  39491. this.setTextureParameters( glTextureType, texture );
  39492. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  39493. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39494. } else if ( texture.isData3DTexture ) {
  39495. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39496. } else if ( ! texture.isVideoTexture ) {
  39497. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39498. }
  39499. backend.set( texture, {
  39500. textureGPU,
  39501. glTextureType,
  39502. glFormat,
  39503. glType,
  39504. glInternalFormat
  39505. } );
  39506. }
  39507. /**
  39508. * Uploads texture buffer data to the GPU memory.
  39509. *
  39510. * @param {WebGLBuffer} buffer - The buffer data.
  39511. * @param {Texture} texture - The texture,
  39512. */
  39513. copyBufferToTexture( buffer, texture ) {
  39514. const { gl, backend } = this;
  39515. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39516. const { width, height } = texture.source.data;
  39517. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39518. backend.state.bindTexture( glTextureType, textureGPU );
  39519. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39520. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39521. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39522. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39523. backend.state.unbindTexture();
  39524. // debug
  39525. // const framebuffer = gl.createFramebuffer();
  39526. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39527. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39528. // const readout = new Float32Array( width * height * 4 );
  39529. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39530. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39531. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39532. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39533. // console.log( readout );
  39534. }
  39535. /**
  39536. * Uploads the updated texture data to the GPU.
  39537. *
  39538. * @param {Texture} texture - The texture.
  39539. * @param {Object} [options={}] - Optional configuration parameter.
  39540. */
  39541. updateTexture( texture, options ) {
  39542. const { gl } = this;
  39543. const { width, height } = options;
  39544. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39545. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39546. return;
  39547. const getImage = ( source ) => {
  39548. if ( source.isDataTexture ) {
  39549. return source.image.data;
  39550. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  39551. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  39552. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  39553. source instanceof OffscreenCanvas ) {
  39554. return source;
  39555. }
  39556. return source.data;
  39557. };
  39558. this.backend.state.bindTexture( glTextureType, textureGPU );
  39559. this.setTextureParameters( glTextureType, texture );
  39560. if ( texture.isCompressedTexture ) {
  39561. const mipmaps = texture.mipmaps;
  39562. const image = options.image;
  39563. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39564. const mipmap = mipmaps[ i ];
  39565. if ( texture.isCompressedArrayTexture ) {
  39566. if ( texture.format !== gl.RGBA ) {
  39567. if ( glFormat !== null ) {
  39568. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  39569. } else {
  39570. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39571. }
  39572. } else {
  39573. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39574. }
  39575. } else {
  39576. if ( glFormat !== null ) {
  39577. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39578. } else {
  39579. console.warn( 'Unsupported compressed texture format' );
  39580. }
  39581. }
  39582. }
  39583. } else if ( texture.isCubeTexture ) {
  39584. const images = options.images;
  39585. for ( let i = 0; i < 6; i ++ ) {
  39586. const image = getImage( images[ i ] );
  39587. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39588. }
  39589. } else if ( texture.isDataArrayTexture ) {
  39590. const image = options.image;
  39591. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39592. } else if ( texture.isData3DTexture ) {
  39593. const image = options.image;
  39594. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39595. } else if ( texture.isVideoTexture ) {
  39596. texture.update();
  39597. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39598. } else {
  39599. const image = getImage( options.image );
  39600. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39601. }
  39602. }
  39603. /**
  39604. * Generates mipmaps for the given texture.
  39605. *
  39606. * @param {Texture} texture - The texture.
  39607. */
  39608. generateMipmaps( texture ) {
  39609. const { gl, backend } = this;
  39610. const { textureGPU, glTextureType } = backend.get( texture );
  39611. backend.state.bindTexture( glTextureType, textureGPU );
  39612. gl.generateMipmap( glTextureType );
  39613. }
  39614. /**
  39615. * Deallocates the render buffers of the given render target.
  39616. *
  39617. * @param {RenderTarget} renderTarget - The render target.
  39618. */
  39619. deallocateRenderBuffers( renderTarget ) {
  39620. const { gl, backend } = this;
  39621. // remove framebuffer reference
  39622. if ( renderTarget ) {
  39623. const renderContextData = backend.get( renderTarget );
  39624. renderContextData.renderBufferStorageSetup = undefined;
  39625. if ( renderContextData.framebuffers ) {
  39626. for ( const cacheKey in renderContextData.framebuffers ) {
  39627. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  39628. }
  39629. delete renderContextData.framebuffers;
  39630. }
  39631. if ( renderContextData.depthRenderbuffer ) {
  39632. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39633. delete renderContextData.depthRenderbuffer;
  39634. }
  39635. if ( renderContextData.stencilRenderbuffer ) {
  39636. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39637. delete renderContextData.stencilRenderbuffer;
  39638. }
  39639. if ( renderContextData.msaaFrameBuffer ) {
  39640. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39641. delete renderContextData.msaaFrameBuffer;
  39642. }
  39643. if ( renderContextData.msaaRenderbuffers ) {
  39644. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39645. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39646. }
  39647. delete renderContextData.msaaRenderbuffers;
  39648. }
  39649. }
  39650. }
  39651. /**
  39652. * Destroys the GPU data for the given texture object.
  39653. *
  39654. * @param {Texture} texture - The texture.
  39655. */
  39656. destroyTexture( texture ) {
  39657. const { gl, backend } = this;
  39658. const { textureGPU, renderTarget } = backend.get( texture );
  39659. this.deallocateRenderBuffers( renderTarget );
  39660. gl.deleteTexture( textureGPU );
  39661. backend.delete( texture );
  39662. }
  39663. /**
  39664. * Copies data of the given source texture to the given destination texture.
  39665. *
  39666. * @param {Texture} srcTexture - The source texture.
  39667. * @param {Texture} dstTexture - The destination texture.
  39668. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39669. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39670. * @param {Number} [level=0] - The mip level to copy.
  39671. */
  39672. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39673. const { gl, backend } = this;
  39674. const { state } = this.backend;
  39675. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39676. let width, height, minX, minY;
  39677. let dstX, dstY;
  39678. if ( srcRegion !== null ) {
  39679. width = srcRegion.max.x - srcRegion.min.x;
  39680. height = srcRegion.max.y - srcRegion.min.y;
  39681. minX = srcRegion.min.x;
  39682. minY = srcRegion.min.y;
  39683. } else {
  39684. width = srcTexture.image.width;
  39685. height = srcTexture.image.height;
  39686. minX = 0;
  39687. minY = 0;
  39688. }
  39689. if ( dstPosition !== null ) {
  39690. dstX = dstPosition.x;
  39691. dstY = dstPosition.y;
  39692. } else {
  39693. dstX = 0;
  39694. dstY = 0;
  39695. }
  39696. state.bindTexture( glTextureType, dstTextureGPU );
  39697. // As another texture upload may have changed pixelStorei
  39698. // parameters, make sure they are correct for the dstTexture
  39699. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39700. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39701. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39702. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39703. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39704. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39705. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39706. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39707. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39708. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39709. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39710. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39711. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39712. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39713. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  39714. const srcTextureData = backend.get( srcTexture );
  39715. const dstTextureData = backend.get( dstTexture );
  39716. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  39717. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  39718. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  39719. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  39720. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  39721. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  39722. let mask = gl.COLOR_BUFFER_BIT;
  39723. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  39724. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  39725. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  39726. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  39727. } else {
  39728. if ( srcTexture.isDataTexture ) {
  39729. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39730. } else {
  39731. if ( srcTexture.isCompressedTexture ) {
  39732. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39733. } else {
  39734. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39735. }
  39736. }
  39737. }
  39738. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39739. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39740. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39741. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39742. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39743. // Generate mipmaps only when copying level 0
  39744. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39745. state.unbindTexture();
  39746. }
  39747. /**
  39748. * Copies the current bound framebuffer to the given texture.
  39749. *
  39750. * @param {Texture} texture - The destination texture.
  39751. * @param {RenderContext} renderContext - The render context.
  39752. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39753. */
  39754. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39755. const { gl } = this;
  39756. const { state } = this.backend;
  39757. const { textureGPU } = this.backend.get( texture );
  39758. const { x, y, z: width, w: height } = rectangle;
  39759. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39760. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  39761. if ( requireDrawFrameBuffer ) {
  39762. const partial = ( x !== 0 || y !== 0 );
  39763. let mask;
  39764. let attachment;
  39765. if ( texture.isDepthTexture === true ) {
  39766. mask = gl.DEPTH_BUFFER_BIT;
  39767. attachment = gl.DEPTH_ATTACHMENT;
  39768. if ( renderContext.stencil ) {
  39769. mask |= gl.STENCIL_BUFFER_BIT;
  39770. }
  39771. } else {
  39772. mask = gl.COLOR_BUFFER_BIT;
  39773. attachment = gl.COLOR_ATTACHMENT0;
  39774. }
  39775. if ( partial ) {
  39776. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  39777. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  39778. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39779. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39780. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39781. const flippedY = srcHeight - y - height;
  39782. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  39783. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39784. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39785. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  39786. state.unbindTexture();
  39787. } else {
  39788. const fb = gl.createFramebuffer();
  39789. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39790. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39791. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39792. gl.deleteFramebuffer( fb );
  39793. }
  39794. } else {
  39795. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39796. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  39797. state.unbindTexture();
  39798. }
  39799. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39800. this.backend._setFramebuffer( renderContext );
  39801. }
  39802. /**
  39803. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  39804. *
  39805. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  39806. * @param {RenderContext} renderContext - The render context.
  39807. */
  39808. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39809. const { gl } = this;
  39810. const renderTarget = renderContext.renderTarget;
  39811. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39812. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39813. if ( depthBuffer && ! stencilBuffer ) {
  39814. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39815. if ( samples > 0 ) {
  39816. if ( depthTexture && depthTexture.isDepthTexture ) {
  39817. if ( depthTexture.type === gl.FLOAT ) {
  39818. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39819. }
  39820. }
  39821. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39822. } else {
  39823. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39824. }
  39825. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39826. } else if ( depthBuffer && stencilBuffer ) {
  39827. if ( samples > 0 ) {
  39828. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39829. } else {
  39830. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39831. }
  39832. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39833. }
  39834. }
  39835. /**
  39836. * Returns texture data as a typed array.
  39837. *
  39838. * @async
  39839. * @param {Texture} texture - The texture to copy.
  39840. * @param {Number} x - The x coordinate of the copy origin.
  39841. * @param {Number} y - The y coordinate of the copy origin.
  39842. * @param {Number} width - The width of the copy.
  39843. * @param {Number} height - The height of the copy.
  39844. * @param {Number} faceIndex - The face index.
  39845. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39846. */
  39847. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  39848. const { backend, gl } = this;
  39849. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  39850. const fb = gl.createFramebuffer();
  39851. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39852. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  39853. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  39854. const typedArrayType = this._getTypedArrayType( glType );
  39855. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  39856. const elementCount = width * height;
  39857. const byteLength = elementCount * bytesPerTexel;
  39858. const buffer = gl.createBuffer();
  39859. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39860. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  39861. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  39862. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39863. await backend.utils._clientWaitAsync();
  39864. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  39865. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39866. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  39867. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39868. gl.deleteFramebuffer( fb );
  39869. return dstBuffer;
  39870. }
  39871. /**
  39872. * Returns the corresponding typed array type for the given WebGL data type.
  39873. *
  39874. * @private
  39875. * @param {GLenum} glType - The WebGL data type.
  39876. * @return {TypedArray.constructor} The typed array type.
  39877. */
  39878. _getTypedArrayType( glType ) {
  39879. const { gl } = this;
  39880. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  39881. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  39882. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  39883. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  39884. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  39885. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  39886. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  39887. if ( glType === gl.FLOAT ) return Float32Array;
  39888. throw new Error( `Unsupported WebGL type: ${glType}` );
  39889. }
  39890. /**
  39891. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  39892. *
  39893. * @private
  39894. * @param {GLenum} glType - The WebGL data type.
  39895. * @param {GLenum} glFormat - The WebGL texture format.
  39896. * @return {Number} The bytes-per-texel.
  39897. */
  39898. _getBytesPerTexel( glType, glFormat ) {
  39899. const { gl } = this;
  39900. let bytesPerComponent = 0;
  39901. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  39902. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  39903. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  39904. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  39905. glType === gl.UNSIGNED_SHORT ||
  39906. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  39907. if ( glType === gl.UNSIGNED_INT ||
  39908. glType === gl.FLOAT ) bytesPerComponent = 4;
  39909. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  39910. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  39911. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  39912. }
  39913. }
  39914. /**
  39915. * A WebGL 2 backend utility module for managing extensions.
  39916. *
  39917. * @private
  39918. */
  39919. class WebGLExtensions {
  39920. /**
  39921. * Constructs a new utility object.
  39922. *
  39923. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39924. */
  39925. constructor( backend ) {
  39926. /**
  39927. * A reference to the WebGL 2 backend.
  39928. *
  39929. * @type {WebGLBackend}
  39930. */
  39931. this.backend = backend;
  39932. /**
  39933. * A reference to the rendering context.
  39934. *
  39935. * @type {WebGL2RenderingContext}
  39936. */
  39937. this.gl = this.backend.gl;
  39938. /**
  39939. * A list with all the supported WebGL extensions.
  39940. *
  39941. * @type {Array<String>}
  39942. */
  39943. this.availableExtensions = this.gl.getSupportedExtensions();
  39944. /**
  39945. * A dictionary with requested WebGL extensions.
  39946. * The key is the name of the extension, the value
  39947. * the requested extension object.
  39948. *
  39949. * @type {Object<String,Object>}
  39950. */
  39951. this.extensions = {};
  39952. }
  39953. /**
  39954. * Returns the extension object for the given extension name.
  39955. *
  39956. * @param {String} name - The extension name.
  39957. * @return {Object} The extension object.
  39958. */
  39959. get( name ) {
  39960. let extension = this.extensions[ name ];
  39961. if ( extension === undefined ) {
  39962. extension = this.gl.getExtension( name );
  39963. this.extensions[ name ] = extension;
  39964. }
  39965. return extension;
  39966. }
  39967. /**
  39968. * Returns `true` if the requested extension is available.
  39969. *
  39970. * @param {String} name - The extension name.
  39971. * @return {Boolean} Whether the given extension is available or not.
  39972. */
  39973. has( name ) {
  39974. return this.availableExtensions.includes( name );
  39975. }
  39976. }
  39977. /**
  39978. * A WebGL 2 backend utility module for managing the device's capabilities.
  39979. *
  39980. * @private
  39981. */
  39982. class WebGLCapabilities {
  39983. /**
  39984. * Constructs a new utility object.
  39985. *
  39986. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39987. */
  39988. constructor( backend ) {
  39989. /**
  39990. * A reference to the WebGL 2 backend.
  39991. *
  39992. * @type {WebGLBackend}
  39993. */
  39994. this.backend = backend;
  39995. /**
  39996. * This value holds the cached max anisotropy value.
  39997. *
  39998. * @type {Number?}
  39999. * @default null
  40000. */
  40001. this.maxAnisotropy = null;
  40002. }
  40003. /**
  40004. * Returns the maximum anisotropy texture filtering value. This value
  40005. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  40006. * WebGL extension.
  40007. *
  40008. * @return {Number} The maximum anisotropy texture filtering value.
  40009. */
  40010. getMaxAnisotropy() {
  40011. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40012. const gl = this.backend.gl;
  40013. const extensions = this.backend.extensions;
  40014. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40015. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40016. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40017. } else {
  40018. this.maxAnisotropy = 0;
  40019. }
  40020. return this.maxAnisotropy;
  40021. }
  40022. }
  40023. const GLFeatureName = {
  40024. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40025. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40026. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40027. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40028. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40029. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40030. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40031. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40032. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40033. };
  40034. class WebGLBufferRenderer {
  40035. constructor( backend ) {
  40036. this.gl = backend.gl;
  40037. this.extensions = backend.extensions;
  40038. this.info = backend.renderer.info;
  40039. this.mode = null;
  40040. this.index = 0;
  40041. this.type = null;
  40042. this.object = null;
  40043. }
  40044. render( start, count ) {
  40045. const { gl, mode, object, type, info, index } = this;
  40046. if ( index !== 0 ) {
  40047. gl.drawElements( mode, count, type, start );
  40048. } else {
  40049. gl.drawArrays( mode, start, count );
  40050. }
  40051. info.update( object, count, mode, 1 );
  40052. }
  40053. renderInstances( start, count, primcount ) {
  40054. const { gl, mode, type, index, object, info } = this;
  40055. if ( primcount === 0 ) return;
  40056. if ( index !== 0 ) {
  40057. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40058. } else {
  40059. gl.drawArraysInstanced( mode, start, count, primcount );
  40060. }
  40061. info.update( object, count, mode, primcount );
  40062. }
  40063. renderMultiDraw( starts, counts, drawCount ) {
  40064. const { extensions, mode, object, info } = this;
  40065. if ( drawCount === 0 ) return;
  40066. const extension = extensions.get( 'WEBGL_multi_draw' );
  40067. if ( extension === null ) {
  40068. for ( let i = 0; i < drawCount; i ++ ) {
  40069. this.render( starts[ i ], counts[ i ] );
  40070. }
  40071. } else {
  40072. if ( this.index !== 0 ) {
  40073. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40074. } else {
  40075. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40076. }
  40077. let elementCount = 0;
  40078. for ( let i = 0; i < drawCount; i ++ ) {
  40079. elementCount += counts[ i ];
  40080. }
  40081. info.update( object, elementCount, mode, 1 );
  40082. }
  40083. }
  40084. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40085. const { extensions, mode, object, info } = this;
  40086. if ( drawCount === 0 ) return;
  40087. const extension = extensions.get( 'WEBGL_multi_draw' );
  40088. if ( extension === null ) {
  40089. for ( let i = 0; i < drawCount; i ++ ) {
  40090. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40091. }
  40092. } else {
  40093. if ( this.index !== 0 ) {
  40094. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40095. } else {
  40096. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40097. }
  40098. let elementCount = 0;
  40099. for ( let i = 0; i < drawCount; i ++ ) {
  40100. elementCount += counts[ i ] * primcount[ i ];
  40101. }
  40102. info.update( object, elementCount, mode, 1 );
  40103. }
  40104. }
  40105. //
  40106. }
  40107. /**
  40108. * A backend implementation targeting WebGL 2.
  40109. *
  40110. * @private
  40111. * @augments Backend
  40112. */
  40113. class WebGLBackend extends Backend {
  40114. /**
  40115. * Constructs a new WebGPU backend.
  40116. *
  40117. * @param {Object} parameters - The configuration parameter.
  40118. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40119. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40120. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40121. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40122. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40123. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  40124. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40125. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  40126. */
  40127. constructor( parameters = {} ) {
  40128. super( parameters );
  40129. /**
  40130. * This flag can be used for type testing.
  40131. *
  40132. * @type {Boolean}
  40133. * @readonly
  40134. * @default true
  40135. */
  40136. this.isWebGLBackend = true;
  40137. /**
  40138. * A reference to a backend module holding shader attribute-related
  40139. * utility functions.
  40140. *
  40141. * @type {WebGLAttributeUtils?}
  40142. * @default null
  40143. */
  40144. this.attributeUtils = null;
  40145. /**
  40146. * A reference to a backend module holding extension-related
  40147. * utility functions.
  40148. *
  40149. * @type {WebGLExtensions?}
  40150. * @default null
  40151. */
  40152. this.extensions = null;
  40153. /**
  40154. * A reference to a backend module holding capability-related
  40155. * utility functions.
  40156. *
  40157. * @type {WebGLCapabilities?}
  40158. * @default null
  40159. */
  40160. this.capabilities = null;
  40161. /**
  40162. * A reference to a backend module holding texture-related
  40163. * utility functions.
  40164. *
  40165. * @type {WebGLTextureUtils?}
  40166. * @default null
  40167. */
  40168. this.textureUtils = null;
  40169. /**
  40170. * A reference to a backend module holding renderer-related
  40171. * utility functions.
  40172. *
  40173. * @type {WebGLBufferRenderer?}
  40174. * @default null
  40175. */
  40176. this.bufferRenderer = null;
  40177. /**
  40178. * A reference to the rendering context.
  40179. *
  40180. * @type {WebGL2RenderingContext?}
  40181. * @default null
  40182. */
  40183. this.gl = null;
  40184. /**
  40185. * A reference to a backend module holding state-related
  40186. * utility functions.
  40187. *
  40188. * @type {WebGLState?}
  40189. * @default null
  40190. */
  40191. this.state = null;
  40192. /**
  40193. * A reference to a backend module holding common
  40194. * utility functions.
  40195. *
  40196. * @type {WebGLUtils?}
  40197. * @default null
  40198. */
  40199. this.utils = null;
  40200. /**
  40201. * Dictionary for caching VAOs.
  40202. *
  40203. * @type {Object<String,WebGLVertexArrayObject>}
  40204. */
  40205. this.vaoCache = {};
  40206. /**
  40207. * Dictionary for caching transform feedback objects.
  40208. *
  40209. * @type {Object<String,WebGLTransformFeedback>}
  40210. */
  40211. this.transformFeedbackCache = {};
  40212. /**
  40213. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  40214. * Only relevant when using compute shaders.
  40215. *
  40216. * @type {Boolean}
  40217. * @default false
  40218. */
  40219. this.discard = false;
  40220. /**
  40221. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  40222. * device does not support the extension.
  40223. *
  40224. * @type {EXTDisjointTimerQueryWebGL2?}
  40225. * @default null
  40226. */
  40227. this.disjoint = null;
  40228. /**
  40229. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  40230. * device does not support the extension.
  40231. *
  40232. * @type {KHRParallelShaderCompile?}
  40233. * @default null
  40234. */
  40235. this.parallel = null;
  40236. /**
  40237. * Whether to track timestamps with a Timestamp Query API or not.
  40238. *
  40239. * @type {Boolean}
  40240. * @default false
  40241. */
  40242. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40243. /**
  40244. * A reference to the current render context.
  40245. *
  40246. * @private
  40247. * @type {RenderContext}
  40248. * @default null
  40249. */
  40250. this._currentContext = null;
  40251. /**
  40252. * A unique collection of bindings.
  40253. *
  40254. * @private
  40255. * @type {WeakSet}
  40256. */
  40257. this._knownBindings = new WeakSet();
  40258. /**
  40259. * The target framebuffer when rendering with
  40260. * the WebXR device API.
  40261. *
  40262. * @private
  40263. * @type {WebGLFramebuffer}
  40264. * @default null
  40265. */
  40266. this._xrFamebuffer = null;
  40267. }
  40268. /**
  40269. * Initializes the backend so it is ready for usage.
  40270. *
  40271. * @param {Renderer} renderer - The renderer.
  40272. */
  40273. init( renderer ) {
  40274. super.init( renderer );
  40275. //
  40276. const parameters = this.parameters;
  40277. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40278. function onContextLost( event ) {
  40279. event.preventDefault();
  40280. const contextLossInfo = {
  40281. api: 'WebGL',
  40282. message: event.statusMessage || 'Unknown reason',
  40283. reason: null,
  40284. originalEvent: event
  40285. };
  40286. renderer.onDeviceLost( contextLossInfo );
  40287. }
  40288. this._onContextLost = onContextLost;
  40289. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40290. this.gl = glContext;
  40291. this.extensions = new WebGLExtensions( this );
  40292. this.capabilities = new WebGLCapabilities( this );
  40293. this.attributeUtils = new WebGLAttributeUtils( this );
  40294. this.textureUtils = new WebGLTextureUtils( this );
  40295. this.bufferRenderer = new WebGLBufferRenderer( this );
  40296. this.state = new WebGLState( this );
  40297. this.utils = new WebGLUtils( this );
  40298. this.extensions.get( 'EXT_color_buffer_float' );
  40299. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40300. this.extensions.get( 'OES_texture_float_linear' );
  40301. this.extensions.get( 'EXT_color_buffer_half_float' );
  40302. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40303. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40304. this.extensions.get( 'WEBGL_multi_draw' );
  40305. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40306. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40307. }
  40308. /**
  40309. * The coordinate system of the backend.
  40310. *
  40311. * @type {Number}
  40312. * @readonly
  40313. */
  40314. get coordinateSystem() {
  40315. return WebGLCoordinateSystem;
  40316. }
  40317. /**
  40318. * This method performs a readback operation by moving buffer data from
  40319. * a storage buffer attribute from the GPU to the CPU.
  40320. *
  40321. * @async
  40322. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40323. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40324. */
  40325. async getArrayBufferAsync( attribute ) {
  40326. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40327. }
  40328. /**
  40329. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40330. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40331. *
  40332. * @async
  40333. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40334. */
  40335. async waitForGPU() {
  40336. await this.utils._clientWaitAsync();
  40337. }
  40338. /**
  40339. * Ensures the backend is XR compatible.
  40340. *
  40341. * @async
  40342. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  40343. */
  40344. async makeXRCompatible() {
  40345. const attributes = this.gl.getContextAttributes();
  40346. if ( attributes.xrCompatible !== true ) {
  40347. await this.gl.makeXRCompatible();
  40348. }
  40349. }
  40350. /**
  40351. * Sets the XR rendering destination.
  40352. *
  40353. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  40354. */
  40355. setXRTarget( xrFamebuffer ) {
  40356. this._xrFamebuffer = xrFamebuffer;
  40357. }
  40358. /**
  40359. * Configures the render target with external textures.
  40360. *
  40361. * @param {RenderTarget} renderTarget - The render target.
  40362. * @param {WebGLTexture} colorTexture - A native color texture.
  40363. * @param {WebGLTexture?} [depthTexture=null] - A native depth texture.
  40364. */
  40365. setRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  40366. this.set( renderTarget.texture, { textureGPU: colorTexture } );
  40367. if ( depthTexture !== null ) {
  40368. this.set( renderTarget.depthTexture, { textureGPU: depthTexture } );
  40369. renderTarget.autoAllocateDepthBuffer = false;
  40370. }
  40371. }
  40372. /**
  40373. * Inits a time stamp query for the given render context.
  40374. *
  40375. * @param {RenderContext} renderContext - The render context.
  40376. */
  40377. initTimestampQuery( renderContext ) {
  40378. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40379. const renderContextData = this.get( renderContext );
  40380. if ( this.queryRunning ) {
  40381. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40382. renderContextData.queryQueue.push( renderContext );
  40383. return;
  40384. }
  40385. if ( renderContextData.activeQuery ) {
  40386. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40387. renderContextData.activeQuery = null;
  40388. }
  40389. renderContextData.activeQuery = this.gl.createQuery();
  40390. if ( renderContextData.activeQuery !== null ) {
  40391. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40392. this.queryRunning = true;
  40393. }
  40394. }
  40395. // timestamp utils
  40396. /**
  40397. * Prepares the timestamp buffer.
  40398. *
  40399. * @param {RenderContext} renderContext - The render context.
  40400. */
  40401. prepareTimestampBuffer( renderContext ) {
  40402. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40403. const renderContextData = this.get( renderContext );
  40404. if ( renderContextData.activeQuery ) {
  40405. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40406. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40407. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40408. renderContextData.activeQuery = null;
  40409. this.queryRunning = false;
  40410. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40411. const nextRenderContext = renderContextData.queryQueue.shift();
  40412. this.initTimestampQuery( nextRenderContext );
  40413. }
  40414. }
  40415. }
  40416. /**
  40417. * Resolves the time stamp for the given render context and type.
  40418. *
  40419. * @async
  40420. * @param {RenderContext} renderContext - The render context.
  40421. * @param {String} type - The render context.
  40422. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  40423. */
  40424. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40425. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40426. const renderContextData = this.get( renderContext );
  40427. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40428. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40429. const queryInfo = renderContextData.gpuQueries[ i ];
  40430. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40431. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40432. if ( available && ! disjoint ) {
  40433. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40434. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40435. this.gl.deleteQuery( queryInfo.query );
  40436. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40437. i --;
  40438. this.renderer.info.updateTimestamp( type, duration );
  40439. }
  40440. }
  40441. }
  40442. /**
  40443. * Returns the backend's rendering context.
  40444. *
  40445. * @return {WebGL2RenderingContext} The rendering context.
  40446. */
  40447. getContext() {
  40448. return this.gl;
  40449. }
  40450. /**
  40451. * This method is executed at the beginning of a render call and prepares
  40452. * the WebGL state for upcoming render calls
  40453. *
  40454. * @param {RenderContext} renderContext - The render context.
  40455. */
  40456. beginRender( renderContext ) {
  40457. const { state, gl } = this;
  40458. const renderContextData = this.get( renderContext );
  40459. //
  40460. //
  40461. this.initTimestampQuery( renderContext );
  40462. renderContextData.previousContext = this._currentContext;
  40463. this._currentContext = renderContext;
  40464. this._setFramebuffer( renderContext );
  40465. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40466. //
  40467. if ( renderContext.viewport ) {
  40468. this.updateViewport( renderContext );
  40469. } else {
  40470. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40471. }
  40472. if ( renderContext.scissor ) {
  40473. const { x, y, width, height } = renderContext.scissorValue;
  40474. state.scissor( x, renderContext.height - height - y, width, height );
  40475. }
  40476. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40477. if ( occlusionQueryCount > 0 ) {
  40478. // Get a reference to the array of objects with queries. The renderContextData property
  40479. // can be changed by another render pass before the async reading of all previous queries complete
  40480. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40481. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40482. renderContextData.lastOcclusionObject = null;
  40483. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40484. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40485. renderContextData.occlusionQueryIndex = 0;
  40486. }
  40487. }
  40488. /**
  40489. * This method is executed at the end of a render call and finalizes work
  40490. * after draw calls.
  40491. *
  40492. * @param {RenderContext} renderContext - The render context.
  40493. */
  40494. finishRender( renderContext ) {
  40495. const { gl, state } = this;
  40496. const renderContextData = this.get( renderContext );
  40497. const previousContext = renderContextData.previousContext;
  40498. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40499. if ( occlusionQueryCount > 0 ) {
  40500. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40501. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40502. }
  40503. this.resolveOccludedAsync( renderContext );
  40504. }
  40505. const textures = renderContext.textures;
  40506. if ( textures !== null ) {
  40507. for ( let i = 0; i < textures.length; i ++ ) {
  40508. const texture = textures[ i ];
  40509. if ( texture.generateMipmaps ) {
  40510. this.generateMipmaps( texture );
  40511. }
  40512. }
  40513. }
  40514. this._currentContext = previousContext;
  40515. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40516. const renderTargetContextData = this.get( renderContext.renderTarget );
  40517. const { samples } = renderContext.renderTarget;
  40518. if ( samples > 0 ) {
  40519. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40520. const mask = gl.COLOR_BUFFER_BIT;
  40521. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40522. const textures = renderContext.textures;
  40523. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40524. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40525. for ( let i = 0; i < textures.length; i ++ ) {
  40526. // TODO Add support for MRT
  40527. if ( renderContext.scissor ) {
  40528. const { x, y, width, height } = renderContext.scissorValue;
  40529. const viewY = renderContext.height - height - y;
  40530. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40531. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40532. } else {
  40533. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40534. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40535. }
  40536. }
  40537. }
  40538. }
  40539. if ( previousContext !== null ) {
  40540. this._setFramebuffer( previousContext );
  40541. if ( previousContext.viewport ) {
  40542. this.updateViewport( previousContext );
  40543. } else {
  40544. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40545. }
  40546. }
  40547. this.prepareTimestampBuffer( renderContext );
  40548. }
  40549. /**
  40550. * This method processes the result of occlusion queries and writes it
  40551. * into render context data.
  40552. *
  40553. * @async
  40554. * @param {RenderContext} renderContext - The render context.
  40555. */
  40556. resolveOccludedAsync( renderContext ) {
  40557. const renderContextData = this.get( renderContext );
  40558. // handle occlusion query results
  40559. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40560. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40561. const occluded = new WeakSet();
  40562. const { gl } = this;
  40563. renderContextData.currentOcclusionQueryObjects = null;
  40564. renderContextData.currentOcclusionQueries = null;
  40565. const check = () => {
  40566. let completed = 0;
  40567. // check all queries and requeue as appropriate
  40568. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40569. const query = currentOcclusionQueries[ i ];
  40570. if ( query === null ) continue;
  40571. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40572. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40573. currentOcclusionQueries[ i ] = null;
  40574. gl.deleteQuery( query );
  40575. completed ++;
  40576. }
  40577. }
  40578. if ( completed < currentOcclusionQueries.length ) {
  40579. requestAnimationFrame( check );
  40580. } else {
  40581. renderContextData.occluded = occluded;
  40582. }
  40583. };
  40584. check();
  40585. }
  40586. }
  40587. /**
  40588. * Returns `true` if the given 3D object is fully occluded by other
  40589. * 3D objects in the scene.
  40590. *
  40591. * @param {RenderContext} renderContext - The render context.
  40592. * @param {Object3D} object - The 3D object to test.
  40593. * @return {Boolean} Whether the 3D object is fully occluded or not.
  40594. */
  40595. isOccluded( renderContext, object ) {
  40596. const renderContextData = this.get( renderContext );
  40597. return renderContextData.occluded && renderContextData.occluded.has( object );
  40598. }
  40599. /**
  40600. * Updates the viewport with the values from the given render context.
  40601. *
  40602. * @param {RenderContext} renderContext - The render context.
  40603. */
  40604. updateViewport( renderContext ) {
  40605. const { state } = this;
  40606. const { x, y, width, height } = renderContext.viewportValue;
  40607. state.viewport( x, renderContext.height - height - y, width, height );
  40608. }
  40609. /**
  40610. * Defines the scissor test.
  40611. *
  40612. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  40613. */
  40614. setScissorTest( boolean ) {
  40615. const state = this.state;
  40616. state.setScissorTest( boolean );
  40617. }
  40618. /**
  40619. * Performs a clear operation.
  40620. *
  40621. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  40622. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  40623. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  40624. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  40625. * @param {Boolean} [setFrameBuffer=true] - TODO.
  40626. */
  40627. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40628. const { gl } = this;
  40629. if ( descriptor === null ) {
  40630. const clearColor = this.getClearColor();
  40631. // premultiply alpha
  40632. clearColor.r *= clearColor.a;
  40633. clearColor.g *= clearColor.a;
  40634. clearColor.b *= clearColor.a;
  40635. descriptor = {
  40636. textures: null,
  40637. clearColorValue: clearColor
  40638. };
  40639. }
  40640. //
  40641. let clear = 0;
  40642. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40643. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40644. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40645. if ( clear !== 0 ) {
  40646. let clearColor;
  40647. if ( descriptor.clearColorValue ) {
  40648. clearColor = descriptor.clearColorValue;
  40649. } else {
  40650. clearColor = this.getClearColor();
  40651. // premultiply alpha
  40652. clearColor.r *= clearColor.a;
  40653. clearColor.g *= clearColor.a;
  40654. clearColor.b *= clearColor.a;
  40655. }
  40656. if ( depth ) this.state.setDepthMask( true );
  40657. if ( descriptor.textures === null ) {
  40658. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40659. gl.clear( clear );
  40660. } else {
  40661. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40662. if ( color ) {
  40663. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40664. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40665. }
  40666. }
  40667. if ( depth && stencil ) {
  40668. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40669. } else if ( depth ) {
  40670. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40671. } else if ( stencil ) {
  40672. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40673. }
  40674. }
  40675. }
  40676. }
  40677. /**
  40678. * This method is executed at the beginning of a compute call and
  40679. * prepares the state for upcoming compute tasks.
  40680. *
  40681. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40682. */
  40683. beginCompute( computeGroup ) {
  40684. const { state, gl } = this;
  40685. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40686. this.initTimestampQuery( computeGroup );
  40687. }
  40688. /**
  40689. * Executes a compute command for the given compute node.
  40690. *
  40691. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40692. * @param {Node} computeNode - The compute node.
  40693. * @param {Array<BindGroup>} bindings - The bindings.
  40694. * @param {ComputePipeline} pipeline - The compute pipeline.
  40695. */
  40696. compute( computeGroup, computeNode, bindings, pipeline ) {
  40697. const { state, gl } = this;
  40698. if ( this.discard === false ) {
  40699. // required here to handle async behaviour of render.compute()
  40700. gl.enable( gl.RASTERIZER_DISCARD );
  40701. this.discard = true;
  40702. }
  40703. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40704. const vaoKey = this._getVaoKey( null, attributes );
  40705. const vaoGPU = this.vaoCache[ vaoKey ];
  40706. if ( vaoGPU === undefined ) {
  40707. this._createVao( null, attributes );
  40708. } else {
  40709. gl.bindVertexArray( vaoGPU );
  40710. }
  40711. state.useProgram( programGPU );
  40712. this._bindUniforms( bindings );
  40713. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40714. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40715. gl.beginTransformFeedback( gl.POINTS );
  40716. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40717. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40718. } else {
  40719. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40720. }
  40721. gl.endTransformFeedback();
  40722. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40723. // switch active buffers
  40724. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40725. const dualAttributeData = transformBuffers[ i ];
  40726. if ( dualAttributeData.pbo ) {
  40727. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40728. }
  40729. dualAttributeData.switchBuffers();
  40730. }
  40731. }
  40732. /**
  40733. * This method is executed at the end of a compute call and
  40734. * finalizes work after compute tasks.
  40735. *
  40736. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40737. */
  40738. finishCompute( computeGroup ) {
  40739. const gl = this.gl;
  40740. this.discard = false;
  40741. gl.disable( gl.RASTERIZER_DISCARD );
  40742. this.prepareTimestampBuffer( computeGroup );
  40743. if ( this._currentContext ) {
  40744. this._setFramebuffer( this._currentContext );
  40745. }
  40746. }
  40747. /**
  40748. * Executes a draw command for the given render object.
  40749. *
  40750. * @param {RenderObject} renderObject - The render object to draw.
  40751. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40752. */
  40753. draw( renderObject/*, info*/ ) {
  40754. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  40755. const { programGPU } = this.get( pipeline );
  40756. const { gl, state } = this;
  40757. const contextData = this.get( context );
  40758. const drawParams = renderObject.getDrawParameters();
  40759. if ( drawParams === null ) return;
  40760. //
  40761. this._bindUniforms( renderObject.getBindings() );
  40762. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40763. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  40764. state.useProgram( programGPU );
  40765. //
  40766. const renderObjectData = this.get( renderObject );
  40767. let vaoGPU = renderObjectData.staticVao;
  40768. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  40769. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40770. vaoGPU = this.vaoCache[ vaoKey ];
  40771. if ( vaoGPU === undefined ) {
  40772. let staticVao;
  40773. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40774. if ( staticVao ) {
  40775. renderObjectData.staticVao = vaoGPU;
  40776. renderObjectData.geometryId = renderObject.geometry.id;
  40777. }
  40778. }
  40779. }
  40780. gl.bindVertexArray( vaoGPU );
  40781. //
  40782. const index = renderObject.getIndex();
  40783. //
  40784. const lastObject = contextData.lastOcclusionObject;
  40785. if ( lastObject !== object && lastObject !== undefined ) {
  40786. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40787. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40788. contextData.occlusionQueryIndex ++;
  40789. }
  40790. if ( object.occlusionTest === true ) {
  40791. const query = gl.createQuery();
  40792. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40793. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40794. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40795. }
  40796. contextData.lastOcclusionObject = object;
  40797. }
  40798. //
  40799. const renderer = this.bufferRenderer;
  40800. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40801. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40802. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40803. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40804. else {
  40805. if ( material.wireframe === true ) {
  40806. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40807. renderer.mode = gl.LINES;
  40808. } else {
  40809. renderer.mode = gl.TRIANGLES;
  40810. }
  40811. }
  40812. //
  40813. const { vertexCount, instanceCount } = drawParams;
  40814. let { firstVertex } = drawParams;
  40815. renderer.object = object;
  40816. if ( index !== null ) {
  40817. firstVertex *= index.array.BYTES_PER_ELEMENT;
  40818. const indexData = this.get( index );
  40819. renderer.index = index.count;
  40820. renderer.type = indexData.type;
  40821. } else {
  40822. renderer.index = 0;
  40823. }
  40824. const draw = () => {
  40825. if ( object.isBatchedMesh ) {
  40826. if ( object._multiDrawInstances !== null ) {
  40827. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40828. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40829. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40830. } else {
  40831. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40832. }
  40833. } else if ( instanceCount > 1 ) {
  40834. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  40835. } else {
  40836. renderer.render( firstVertex, vertexCount );
  40837. }
  40838. };
  40839. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  40840. const cameraData = this.get( renderObject.camera );
  40841. const cameras = renderObject.camera.cameras;
  40842. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  40843. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  40844. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  40845. const indexesGPU = [];
  40846. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40847. const bufferGPU = gl.createBuffer();
  40848. data[ 0 ] = i;
  40849. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40850. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  40851. indexesGPU.push( bufferGPU );
  40852. }
  40853. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  40854. }
  40855. const cameraIndexData = this.get( cameraIndex );
  40856. const pixelRatio = this.renderer.getPixelRatio();
  40857. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40858. const subCamera = cameras[ i ];
  40859. if ( object.layers.test( subCamera.layers ) ) {
  40860. const vp = subCamera.viewport;
  40861. const x = vp.x * pixelRatio;
  40862. const y = vp.y * pixelRatio;
  40863. const width = vp.width * pixelRatio;
  40864. const height = vp.height * pixelRatio;
  40865. state.viewport(
  40866. Math.floor( x ),
  40867. Math.floor( renderObject.context.height - height - y ),
  40868. Math.floor( width ),
  40869. Math.floor( height )
  40870. );
  40871. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  40872. draw();
  40873. }
  40874. }
  40875. } else {
  40876. draw();
  40877. }
  40878. //
  40879. gl.bindVertexArray( null );
  40880. }
  40881. /**
  40882. * Explain why always null is returned.
  40883. *
  40884. * @param {RenderObject} renderObject - The render object.
  40885. * @return {Boolean} Whether the render pipeline requires an update or not.
  40886. */
  40887. needsRenderUpdate( /*renderObject*/ ) {
  40888. return false;
  40889. }
  40890. /**
  40891. * Explain why no cache key is computed.
  40892. *
  40893. * @param {RenderObject} renderObject - The render object.
  40894. * @return {String} The cache key.
  40895. */
  40896. getRenderCacheKey( /*renderObject*/ ) {
  40897. return '';
  40898. }
  40899. // textures
  40900. /**
  40901. * Creates a default texture for the given texture that can be used
  40902. * as a placeholder until the actual texture is ready for usage.
  40903. *
  40904. * @param {Texture} texture - The texture to create a default texture for.
  40905. */
  40906. createDefaultTexture( texture ) {
  40907. this.textureUtils.createDefaultTexture( texture );
  40908. }
  40909. /**
  40910. * Defines a texture on the GPU for the given texture object.
  40911. *
  40912. * @param {Texture} texture - The texture.
  40913. * @param {Object} [options={}] - Optional configuration parameter.
  40914. */
  40915. createTexture( texture, options ) {
  40916. this.textureUtils.createTexture( texture, options );
  40917. }
  40918. /**
  40919. * Uploads the updated texture data to the GPU.
  40920. *
  40921. * @param {Texture} texture - The texture.
  40922. * @param {Object} [options={}] - Optional configuration parameter.
  40923. */
  40924. updateTexture( texture, options ) {
  40925. this.textureUtils.updateTexture( texture, options );
  40926. }
  40927. /**
  40928. * Generates mipmaps for the given texture.
  40929. *
  40930. * @param {Texture} texture - The texture.
  40931. */
  40932. generateMipmaps( texture ) {
  40933. this.textureUtils.generateMipmaps( texture );
  40934. }
  40935. /**
  40936. * Destroys the GPU data for the given texture object.
  40937. *
  40938. * @param {Texture} texture - The texture.
  40939. */
  40940. destroyTexture( texture ) {
  40941. this.textureUtils.destroyTexture( texture );
  40942. }
  40943. /**
  40944. * Returns texture data as a typed array.
  40945. *
  40946. * @async
  40947. * @param {Texture} texture - The texture to copy.
  40948. * @param {Number} x - The x coordinate of the copy origin.
  40949. * @param {Number} y - The y coordinate of the copy origin.
  40950. * @param {Number} width - The width of the copy.
  40951. * @param {Number} height - The height of the copy.
  40952. * @param {Number} faceIndex - The face index.
  40953. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40954. */
  40955. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40956. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  40957. }
  40958. /**
  40959. * This method does nothing since WebGL 2 has no concept of samplers.
  40960. *
  40961. * @param {Texture} texture - The texture to create the sampler for.
  40962. */
  40963. createSampler( /*texture*/ ) {
  40964. //console.warn( 'Abstract class.' );
  40965. }
  40966. /**
  40967. * This method does nothing since WebGL 2 has no concept of samplers.
  40968. *
  40969. * @param {Texture} texture - The texture to destroy the sampler for.
  40970. */
  40971. destroySampler( /*texture*/ ) {}
  40972. // node builder
  40973. /**
  40974. * Returns a node builder for the given render object.
  40975. *
  40976. * @param {RenderObject} object - The render object.
  40977. * @param {Renderer} renderer - The renderer.
  40978. * @return {GLSLNodeBuilder} The node builder.
  40979. */
  40980. createNodeBuilder( object, renderer ) {
  40981. return new GLSLNodeBuilder( object, renderer );
  40982. }
  40983. // program
  40984. /**
  40985. * Creates a shader program from the given programmable stage.
  40986. *
  40987. * @param {ProgrammableStage} program - The programmable stage.
  40988. */
  40989. createProgram( program ) {
  40990. const gl = this.gl;
  40991. const { stage, code } = program;
  40992. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40993. gl.shaderSource( shader, code );
  40994. gl.compileShader( shader );
  40995. this.set( program, {
  40996. shaderGPU: shader
  40997. } );
  40998. }
  40999. /**
  41000. * Destroys the shader program of the given programmable stage.
  41001. *
  41002. * @param {ProgrammableStage} program - The programmable stage.
  41003. */
  41004. destroyProgram( program ) {
  41005. this.delete( program );
  41006. }
  41007. /**
  41008. * Creates a render pipeline for the given render object.
  41009. *
  41010. * @param {RenderObject} renderObject - The render object.
  41011. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41012. */
  41013. createRenderPipeline( renderObject, promises ) {
  41014. const gl = this.gl;
  41015. const pipeline = renderObject.pipeline;
  41016. // Program
  41017. const { fragmentProgram, vertexProgram } = pipeline;
  41018. const programGPU = gl.createProgram();
  41019. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41020. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41021. gl.attachShader( programGPU, fragmentShader );
  41022. gl.attachShader( programGPU, vertexShader );
  41023. gl.linkProgram( programGPU );
  41024. this.set( pipeline, {
  41025. programGPU,
  41026. fragmentShader,
  41027. vertexShader
  41028. } );
  41029. if ( promises !== null && this.parallel ) {
  41030. const p = new Promise( ( resolve /*, reject*/ ) => {
  41031. const parallel = this.parallel;
  41032. const checkStatus = () => {
  41033. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41034. this._completeCompile( renderObject, pipeline );
  41035. resolve();
  41036. } else {
  41037. requestAnimationFrame( checkStatus );
  41038. }
  41039. };
  41040. checkStatus();
  41041. } );
  41042. promises.push( p );
  41043. return;
  41044. }
  41045. this._completeCompile( renderObject, pipeline );
  41046. }
  41047. /**
  41048. * Formats the source code of error messages.
  41049. *
  41050. * @private
  41051. * @param {String} string - The code.
  41052. * @param {Number} errorLine - The error line.
  41053. * @return {String} The formatted code.
  41054. */
  41055. _handleSource( string, errorLine ) {
  41056. const lines = string.split( '\n' );
  41057. const lines2 = [];
  41058. const from = Math.max( errorLine - 6, 0 );
  41059. const to = Math.min( errorLine + 6, lines.length );
  41060. for ( let i = from; i < to; i ++ ) {
  41061. const line = i + 1;
  41062. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41063. }
  41064. return lines2.join( '\n' );
  41065. }
  41066. /**
  41067. * Gets the shader compilation errors from the info log.
  41068. *
  41069. * @private
  41070. * @param {WebGL2RenderingContext} gl - The rendering context.
  41071. * @param {WebGLShader} shader - The WebGL shader object.
  41072. * @param {String} type - The shader type.
  41073. * @return {String} The shader errors.
  41074. */
  41075. _getShaderErrors( gl, shader, type ) {
  41076. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41077. const errors = gl.getShaderInfoLog( shader ).trim();
  41078. if ( status && errors === '' ) return '';
  41079. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41080. if ( errorMatches ) {
  41081. const errorLine = parseInt( errorMatches[ 1 ] );
  41082. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41083. } else {
  41084. return errors;
  41085. }
  41086. }
  41087. /**
  41088. * Logs shader compilation errors.
  41089. *
  41090. * @private
  41091. * @param {WebGLProgram} programGPU - The WebGL program.
  41092. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  41093. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  41094. */
  41095. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41096. if ( this.renderer.debug.checkShaderErrors ) {
  41097. const gl = this.gl;
  41098. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41099. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41100. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41101. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41102. } else {
  41103. // default error reporting
  41104. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41105. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41106. console.error(
  41107. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41108. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41109. 'Program Info Log: ' + programLog + '\n' +
  41110. vertexErrors + '\n' +
  41111. fragmentErrors
  41112. );
  41113. }
  41114. } else if ( programLog !== '' ) {
  41115. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41116. }
  41117. }
  41118. }
  41119. /**
  41120. * Completes the shader program setup for the given render object.
  41121. *
  41122. * @private
  41123. * @param {RenderObject} renderObject - The render object.
  41124. * @param {RenderPipeline} pipeline - The render pipeline.
  41125. */
  41126. _completeCompile( renderObject, pipeline ) {
  41127. const { state, gl } = this;
  41128. const pipelineData = this.get( pipeline );
  41129. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41130. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41131. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41132. }
  41133. state.useProgram( programGPU );
  41134. // Bindings
  41135. const bindings = renderObject.getBindings();
  41136. this._setupBindings( bindings, programGPU );
  41137. //
  41138. this.set( pipeline, {
  41139. programGPU
  41140. } );
  41141. }
  41142. /**
  41143. * Creates a compute pipeline for the given compute node.
  41144. *
  41145. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41146. * @param {Array<BindGroup>} bindings - The bindings.
  41147. */
  41148. createComputePipeline( computePipeline, bindings ) {
  41149. const { state, gl } = this;
  41150. // Program
  41151. const fragmentProgram = {
  41152. stage: 'fragment',
  41153. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41154. };
  41155. this.createProgram( fragmentProgram );
  41156. const { computeProgram } = computePipeline;
  41157. const programGPU = gl.createProgram();
  41158. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41159. const vertexShader = this.get( computeProgram ).shaderGPU;
  41160. const transforms = computeProgram.transforms;
  41161. const transformVaryingNames = [];
  41162. const transformAttributeNodes = [];
  41163. for ( let i = 0; i < transforms.length; i ++ ) {
  41164. const transform = transforms[ i ];
  41165. transformVaryingNames.push( transform.varyingName );
  41166. transformAttributeNodes.push( transform.attributeNode );
  41167. }
  41168. gl.attachShader( programGPU, fragmentShader );
  41169. gl.attachShader( programGPU, vertexShader );
  41170. gl.transformFeedbackVaryings(
  41171. programGPU,
  41172. transformVaryingNames,
  41173. gl.SEPARATE_ATTRIBS
  41174. );
  41175. gl.linkProgram( programGPU );
  41176. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41177. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41178. }
  41179. state.useProgram( programGPU );
  41180. // Bindings
  41181. this._setupBindings( bindings, programGPU );
  41182. const attributeNodes = computeProgram.attributes;
  41183. const attributes = [];
  41184. const transformBuffers = [];
  41185. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41186. const attribute = attributeNodes[ i ].node.attribute;
  41187. attributes.push( attribute );
  41188. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41189. }
  41190. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41191. const attribute = transformAttributeNodes[ i ].attribute;
  41192. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41193. const attributeData = this.get( attribute );
  41194. transformBuffers.push( attributeData );
  41195. }
  41196. //
  41197. this.set( computePipeline, {
  41198. programGPU,
  41199. transformBuffers,
  41200. attributes
  41201. } );
  41202. }
  41203. /**
  41204. * Creates bindings from the given bind group definition.
  41205. *
  41206. * @param {BindGroup} bindGroup - The bind group.
  41207. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41208. * @param {Number} cacheIndex - The cache index.
  41209. * @param {Number} version - The version.
  41210. */
  41211. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  41212. if ( this._knownBindings.has( bindings ) === false ) {
  41213. this._knownBindings.add( bindings );
  41214. let uniformBuffers = 0;
  41215. let textures = 0;
  41216. for ( const bindGroup of bindings ) {
  41217. this.set( bindGroup, {
  41218. textures: textures,
  41219. uniformBuffers: uniformBuffers
  41220. } );
  41221. for ( const binding of bindGroup.bindings ) {
  41222. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41223. if ( binding.isSampledTexture ) textures ++;
  41224. }
  41225. }
  41226. }
  41227. this.updateBindings( bindGroup, bindings );
  41228. }
  41229. /**
  41230. * Updates the given bind group definition.
  41231. *
  41232. * @param {BindGroup} bindGroup - The bind group.
  41233. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41234. * @param {Number} cacheIndex - The cache index.
  41235. * @param {Number} version - The version.
  41236. */
  41237. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  41238. const { gl } = this;
  41239. const bindGroupData = this.get( bindGroup );
  41240. let i = bindGroupData.uniformBuffers;
  41241. let t = bindGroupData.textures;
  41242. for ( const binding of bindGroup.bindings ) {
  41243. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41244. const data = binding.buffer;
  41245. const bufferGPU = gl.createBuffer();
  41246. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41247. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41248. this.set( binding, {
  41249. index: i ++,
  41250. bufferGPU
  41251. } );
  41252. } else if ( binding.isSampledTexture ) {
  41253. const { textureGPU, glTextureType } = this.get( binding.texture );
  41254. this.set( binding, {
  41255. index: t ++,
  41256. textureGPU,
  41257. glTextureType
  41258. } );
  41259. }
  41260. }
  41261. }
  41262. /**
  41263. * Updates a buffer binding.
  41264. *
  41265. * @param {Buffer} binding - The buffer binding to update.
  41266. */
  41267. updateBinding( binding ) {
  41268. const gl = this.gl;
  41269. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41270. const bindingData = this.get( binding );
  41271. const bufferGPU = bindingData.bufferGPU;
  41272. const data = binding.buffer;
  41273. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41274. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41275. }
  41276. }
  41277. // attributes
  41278. /**
  41279. * Creates the GPU buffer of an indexed shader attribute.
  41280. *
  41281. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41282. */
  41283. createIndexAttribute( attribute ) {
  41284. const gl = this.gl;
  41285. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41286. }
  41287. /**
  41288. * Creates the GPU buffer of a shader attribute.
  41289. *
  41290. * @param {BufferAttribute} attribute - The buffer attribute.
  41291. */
  41292. createAttribute( attribute ) {
  41293. if ( this.has( attribute ) ) return;
  41294. const gl = this.gl;
  41295. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41296. }
  41297. /**
  41298. * Creates the GPU buffer of a storage attribute.
  41299. *
  41300. * @param {BufferAttribute} attribute - The buffer attribute.
  41301. */
  41302. createStorageAttribute( attribute ) {
  41303. if ( this.has( attribute ) ) return;
  41304. const gl = this.gl;
  41305. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41306. }
  41307. /**
  41308. * Updates the GPU buffer of a shader attribute.
  41309. *
  41310. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41311. */
  41312. updateAttribute( attribute ) {
  41313. this.attributeUtils.updateAttribute( attribute );
  41314. }
  41315. /**
  41316. * Destroys the GPU buffer of a shader attribute.
  41317. *
  41318. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41319. */
  41320. destroyAttribute( attribute ) {
  41321. this.attributeUtils.destroyAttribute( attribute );
  41322. }
  41323. /**
  41324. * Checks if the given feature is supported by the backend.
  41325. *
  41326. * @param {String} name - The feature's name.
  41327. * @return {Boolean} Whether the feature is supported or not.
  41328. */
  41329. hasFeature( name ) {
  41330. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41331. const extensions = this.extensions;
  41332. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41333. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41334. }
  41335. return false;
  41336. }
  41337. /**
  41338. * Returns the maximum anisotropy texture filtering value.
  41339. *
  41340. * @return {Number} The maximum anisotropy texture filtering value.
  41341. */
  41342. getMaxAnisotropy() {
  41343. return this.capabilities.getMaxAnisotropy();
  41344. }
  41345. /**
  41346. * Copies data of the given source texture to the given destination texture.
  41347. *
  41348. * @param {Texture} srcTexture - The source texture.
  41349. * @param {Texture} dstTexture - The destination texture.
  41350. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  41351. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  41352. * @param {Number} [level=0] - The mip level to copy.
  41353. */
  41354. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41355. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41356. }
  41357. /**
  41358. * Copies the current bound framebuffer to the given texture.
  41359. *
  41360. * @param {Texture} texture - The destination texture.
  41361. * @param {RenderContext} renderContext - The render context.
  41362. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41363. */
  41364. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41365. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41366. }
  41367. /**
  41368. * Configures the active framebuffer from the given render context.
  41369. *
  41370. * @private
  41371. * @param {RenderContext} descriptor - The render context.
  41372. */
  41373. _setFramebuffer( descriptor ) {
  41374. const { gl, state } = this;
  41375. let currentFrameBuffer = null;
  41376. if ( descriptor.textures !== null ) {
  41377. const renderTarget = descriptor.renderTarget;
  41378. const renderTargetContextData = this.get( renderTarget );
  41379. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41380. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41381. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  41382. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  41383. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  41384. const hasExternalTextures = renderTarget.hasExternalTextures === true;
  41385. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41386. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41387. const cacheKey = getCacheKey( descriptor );
  41388. let fb;
  41389. if ( isCube ) {
  41390. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41391. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41392. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  41393. fb = this._xrFamebuffer;
  41394. } else {
  41395. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41396. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41397. }
  41398. if ( fb === undefined ) {
  41399. fb = gl.createFramebuffer();
  41400. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41401. const textures = descriptor.textures;
  41402. if ( isCube ) {
  41403. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41404. const { textureGPU } = this.get( textures[ 0 ] );
  41405. const cubeFace = this.renderer._activeCubeFace;
  41406. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41407. } else {
  41408. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41409. for ( let i = 0; i < textures.length; i ++ ) {
  41410. const texture = textures[ i ];
  41411. const textureData = this.get( texture );
  41412. textureData.renderTarget = descriptor.renderTarget;
  41413. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41414. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41415. if ( isRenderTarget3D || isRenderTargetArray ) {
  41416. const layer = this.renderer._activeCubeFace;
  41417. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  41418. } else {
  41419. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41420. }
  41421. }
  41422. state.drawBuffers( descriptor, fb );
  41423. }
  41424. if ( descriptor.depthTexture !== null ) {
  41425. const textureData = this.get( descriptor.depthTexture );
  41426. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41427. textureData.renderTarget = descriptor.renderTarget;
  41428. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41429. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41430. }
  41431. } else {
  41432. // rebind external XR textures
  41433. if ( isXRRenderTarget && hasExternalTextures ) {
  41434. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41435. // rebind color
  41436. const textureData = this.get( descriptor.textures[ 0 ] );
  41437. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41438. // rebind depth
  41439. if ( descriptor.depthTexture !== null ) {
  41440. const textureData = this.get( descriptor.depthTexture );
  41441. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41442. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41443. }
  41444. }
  41445. }
  41446. if ( samples > 0 ) {
  41447. if ( msaaFb === undefined ) {
  41448. const invalidationArray = [];
  41449. msaaFb = gl.createFramebuffer();
  41450. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41451. const msaaRenderbuffers = [];
  41452. const textures = descriptor.textures;
  41453. for ( let i = 0; i < textures.length; i ++ ) {
  41454. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41455. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41456. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41457. if ( depthBuffer ) {
  41458. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41459. invalidationArray.push( depthStyle );
  41460. }
  41461. const texture = descriptor.textures[ i ];
  41462. const textureData = this.get( texture );
  41463. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41464. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41465. }
  41466. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41467. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41468. if ( depthRenderbuffer === undefined ) {
  41469. depthRenderbuffer = gl.createRenderbuffer();
  41470. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41471. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41472. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41473. invalidationArray.push( depthStyle );
  41474. }
  41475. renderTargetContextData.invalidationArray = invalidationArray;
  41476. }
  41477. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41478. } else {
  41479. currentFrameBuffer = fb;
  41480. }
  41481. }
  41482. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41483. }
  41484. /**
  41485. * Computes the VAO key for the given index and attributes.
  41486. *
  41487. * @private
  41488. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41489. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41490. * @return {String} The VAO key.
  41491. */
  41492. _getVaoKey( index, attributes ) {
  41493. let key = '';
  41494. if ( index !== null ) {
  41495. const indexData = this.get( index );
  41496. key += ':' + indexData.id;
  41497. }
  41498. for ( let i = 0; i < attributes.length; i ++ ) {
  41499. const attributeData = this.get( attributes[ i ] );
  41500. key += ':' + attributeData.id;
  41501. }
  41502. return key;
  41503. }
  41504. /**
  41505. * Creates a VAO from the index and attributes.
  41506. *
  41507. * @private
  41508. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41509. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41510. * @return {Object} The VAO data.
  41511. */
  41512. _createVao( index, attributes ) {
  41513. const { gl } = this;
  41514. const vaoGPU = gl.createVertexArray();
  41515. let key = '';
  41516. let staticVao = true;
  41517. gl.bindVertexArray( vaoGPU );
  41518. if ( index !== null ) {
  41519. const indexData = this.get( index );
  41520. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41521. key += ':' + indexData.id;
  41522. }
  41523. for ( let i = 0; i < attributes.length; i ++ ) {
  41524. const attribute = attributes[ i ];
  41525. const attributeData = this.get( attribute );
  41526. key += ':' + attributeData.id;
  41527. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41528. gl.enableVertexAttribArray( i );
  41529. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41530. let stride, offset;
  41531. if ( attribute.isInterleavedBufferAttribute === true ) {
  41532. stride = attribute.data.stride * attributeData.bytesPerElement;
  41533. offset = attribute.offset * attributeData.bytesPerElement;
  41534. } else {
  41535. stride = 0;
  41536. offset = 0;
  41537. }
  41538. if ( attributeData.isInteger ) {
  41539. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41540. } else {
  41541. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41542. }
  41543. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41544. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41545. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41546. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41547. }
  41548. }
  41549. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41550. this.vaoCache[ key ] = vaoGPU;
  41551. return { vaoGPU, staticVao };
  41552. }
  41553. /**
  41554. * Creates a transform feedback from the given transform buffers.
  41555. *
  41556. * @private
  41557. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  41558. * @return {WebGLTransformFeedback} The transform feedback.
  41559. */
  41560. _getTransformFeedback( transformBuffers ) {
  41561. let key = '';
  41562. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41563. key += ':' + transformBuffers[ i ].id;
  41564. }
  41565. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41566. if ( transformFeedbackGPU !== undefined ) {
  41567. return transformFeedbackGPU;
  41568. }
  41569. const { gl } = this;
  41570. transformFeedbackGPU = gl.createTransformFeedback();
  41571. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41572. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41573. const attributeData = transformBuffers[ i ];
  41574. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41575. }
  41576. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41577. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41578. return transformFeedbackGPU;
  41579. }
  41580. /**
  41581. * Setups the given bindings.
  41582. *
  41583. * @private
  41584. * @param {Array<BindGroup>} bindings - The bindings.
  41585. * @param {WebGLProgram} programGPU - The WebGL program.
  41586. */
  41587. _setupBindings( bindings, programGPU ) {
  41588. const gl = this.gl;
  41589. for ( const bindGroup of bindings ) {
  41590. for ( const binding of bindGroup.bindings ) {
  41591. const bindingData = this.get( binding );
  41592. const index = bindingData.index;
  41593. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41594. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41595. gl.uniformBlockBinding( programGPU, location, index );
  41596. } else if ( binding.isSampledTexture ) {
  41597. const location = gl.getUniformLocation( programGPU, binding.name );
  41598. gl.uniform1i( location, index );
  41599. }
  41600. }
  41601. }
  41602. }
  41603. /**
  41604. * Binds the given uniforms.
  41605. *
  41606. * @private
  41607. * @param {Array<BindGroup>} bindings - The bindings.
  41608. */
  41609. _bindUniforms( bindings ) {
  41610. const { gl, state } = this;
  41611. for ( const bindGroup of bindings ) {
  41612. for ( const binding of bindGroup.bindings ) {
  41613. const bindingData = this.get( binding );
  41614. const index = bindingData.index;
  41615. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41616. // TODO USE bindBufferRange to group multiple uniform buffers
  41617. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41618. } else if ( binding.isSampledTexture ) {
  41619. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41620. }
  41621. }
  41622. }
  41623. }
  41624. /**
  41625. * Frees internal resources.
  41626. */
  41627. dispose() {
  41628. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41629. }
  41630. }
  41631. const GPUPrimitiveTopology = {
  41632. PointList: 'point-list',
  41633. LineList: 'line-list',
  41634. LineStrip: 'line-strip',
  41635. TriangleList: 'triangle-list',
  41636. TriangleStrip: 'triangle-strip',
  41637. };
  41638. const GPUCompareFunction = {
  41639. Never: 'never',
  41640. Less: 'less',
  41641. Equal: 'equal',
  41642. LessEqual: 'less-equal',
  41643. Greater: 'greater',
  41644. NotEqual: 'not-equal',
  41645. GreaterEqual: 'greater-equal',
  41646. Always: 'always'
  41647. };
  41648. const GPUStoreOp = {
  41649. Store: 'store',
  41650. Discard: 'discard'
  41651. };
  41652. const GPULoadOp = {
  41653. Load: 'load',
  41654. Clear: 'clear'
  41655. };
  41656. const GPUFrontFace = {
  41657. CCW: 'ccw',
  41658. CW: 'cw'
  41659. };
  41660. const GPUCullMode = {
  41661. None: 'none',
  41662. Front: 'front',
  41663. Back: 'back'
  41664. };
  41665. const GPUIndexFormat = {
  41666. Uint16: 'uint16',
  41667. Uint32: 'uint32'
  41668. };
  41669. const GPUTextureFormat = {
  41670. // 8-bit formats
  41671. R8Unorm: 'r8unorm',
  41672. R8Snorm: 'r8snorm',
  41673. R8Uint: 'r8uint',
  41674. R8Sint: 'r8sint',
  41675. // 16-bit formats
  41676. R16Uint: 'r16uint',
  41677. R16Sint: 'r16sint',
  41678. R16Float: 'r16float',
  41679. RG8Unorm: 'rg8unorm',
  41680. RG8Snorm: 'rg8snorm',
  41681. RG8Uint: 'rg8uint',
  41682. RG8Sint: 'rg8sint',
  41683. // 32-bit formats
  41684. R32Uint: 'r32uint',
  41685. R32Sint: 'r32sint',
  41686. R32Float: 'r32float',
  41687. RG16Uint: 'rg16uint',
  41688. RG16Sint: 'rg16sint',
  41689. RG16Float: 'rg16float',
  41690. RGBA8Unorm: 'rgba8unorm',
  41691. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  41692. RGBA8Snorm: 'rgba8snorm',
  41693. RGBA8Uint: 'rgba8uint',
  41694. RGBA8Sint: 'rgba8sint',
  41695. BGRA8Unorm: 'bgra8unorm',
  41696. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  41697. // Packed 32-bit formats
  41698. RGB9E5UFloat: 'rgb9e5ufloat',
  41699. RGB10A2Unorm: 'rgb10a2unorm',
  41700. RG11B10uFloat: 'rgb10a2unorm',
  41701. // 64-bit formats
  41702. RG32Uint: 'rg32uint',
  41703. RG32Sint: 'rg32sint',
  41704. RG32Float: 'rg32float',
  41705. RGBA16Uint: 'rgba16uint',
  41706. RGBA16Sint: 'rgba16sint',
  41707. RGBA16Float: 'rgba16float',
  41708. // 128-bit formats
  41709. RGBA32Uint: 'rgba32uint',
  41710. RGBA32Sint: 'rgba32sint',
  41711. RGBA32Float: 'rgba32float',
  41712. // Depth and stencil formats
  41713. Stencil8: 'stencil8',
  41714. Depth16Unorm: 'depth16unorm',
  41715. Depth24Plus: 'depth24plus',
  41716. Depth24PlusStencil8: 'depth24plus-stencil8',
  41717. Depth32Float: 'depth32float',
  41718. // 'depth32float-stencil8' extension
  41719. Depth32FloatStencil8: 'depth32float-stencil8',
  41720. // BC compressed formats usable if 'texture-compression-bc' is both
  41721. // supported by the device/user agent and enabled in requestDevice.
  41722. BC1RGBAUnorm: 'bc1-rgba-unorm',
  41723. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  41724. BC2RGBAUnorm: 'bc2-rgba-unorm',
  41725. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  41726. BC3RGBAUnorm: 'bc3-rgba-unorm',
  41727. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  41728. BC4RUnorm: 'bc4-r-unorm',
  41729. BC4RSnorm: 'bc4-r-snorm',
  41730. BC5RGUnorm: 'bc5-rg-unorm',
  41731. BC5RGSnorm: 'bc5-rg-snorm',
  41732. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  41733. BC6HRGBFloat: 'bc6h-rgb-float',
  41734. BC7RGBAUnorm: 'bc7-rgba-unorm',
  41735. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  41736. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  41737. // supported by the device/user agent and enabled in requestDevice.
  41738. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  41739. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  41740. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  41741. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  41742. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  41743. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  41744. EACR11Unorm: 'eac-r11unorm',
  41745. EACR11Snorm: 'eac-r11snorm',
  41746. EACRG11Unorm: 'eac-rg11unorm',
  41747. EACRG11Snorm: 'eac-rg11snorm',
  41748. // ASTC compressed formats usable if 'texture-compression-astc' is both
  41749. // supported by the device/user agent and enabled in requestDevice.
  41750. ASTC4x4Unorm: 'astc-4x4-unorm',
  41751. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  41752. ASTC5x4Unorm: 'astc-5x4-unorm',
  41753. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  41754. ASTC5x5Unorm: 'astc-5x5-unorm',
  41755. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  41756. ASTC6x5Unorm: 'astc-6x5-unorm',
  41757. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  41758. ASTC6x6Unorm: 'astc-6x6-unorm',
  41759. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  41760. ASTC8x5Unorm: 'astc-8x5-unorm',
  41761. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  41762. ASTC8x6Unorm: 'astc-8x6-unorm',
  41763. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  41764. ASTC8x8Unorm: 'astc-8x8-unorm',
  41765. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  41766. ASTC10x5Unorm: 'astc-10x5-unorm',
  41767. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  41768. ASTC10x6Unorm: 'astc-10x6-unorm',
  41769. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  41770. ASTC10x8Unorm: 'astc-10x8-unorm',
  41771. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  41772. ASTC10x10Unorm: 'astc-10x10-unorm',
  41773. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  41774. ASTC12x10Unorm: 'astc-12x10-unorm',
  41775. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  41776. ASTC12x12Unorm: 'astc-12x12-unorm',
  41777. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  41778. };
  41779. const GPUAddressMode = {
  41780. ClampToEdge: 'clamp-to-edge',
  41781. Repeat: 'repeat',
  41782. MirrorRepeat: 'mirror-repeat'
  41783. };
  41784. const GPUFilterMode = {
  41785. Linear: 'linear',
  41786. Nearest: 'nearest'
  41787. };
  41788. const GPUBlendFactor = {
  41789. Zero: 'zero',
  41790. One: 'one',
  41791. Src: 'src',
  41792. OneMinusSrc: 'one-minus-src',
  41793. SrcAlpha: 'src-alpha',
  41794. OneMinusSrcAlpha: 'one-minus-src-alpha',
  41795. Dst: 'dst',
  41796. OneMinusDstColor: 'one-minus-dst',
  41797. DstAlpha: 'dst-alpha',
  41798. OneMinusDstAlpha: 'one-minus-dst-alpha',
  41799. SrcAlphaSaturated: 'src-alpha-saturated',
  41800. Constant: 'constant',
  41801. OneMinusConstant: 'one-minus-constant'
  41802. };
  41803. const GPUBlendOperation = {
  41804. Add: 'add',
  41805. Subtract: 'subtract',
  41806. ReverseSubtract: 'reverse-subtract',
  41807. Min: 'min',
  41808. Max: 'max'
  41809. };
  41810. const GPUColorWriteFlags = {
  41811. None: 0,
  41812. Red: 0x1,
  41813. Green: 0x2,
  41814. Blue: 0x4,
  41815. Alpha: 0x8,
  41816. All: 0xF
  41817. };
  41818. const GPUStencilOperation = {
  41819. Keep: 'keep',
  41820. Zero: 'zero',
  41821. Replace: 'replace',
  41822. Invert: 'invert',
  41823. IncrementClamp: 'increment-clamp',
  41824. DecrementClamp: 'decrement-clamp',
  41825. IncrementWrap: 'increment-wrap',
  41826. DecrementWrap: 'decrement-wrap'
  41827. };
  41828. const GPUBufferBindingType = {
  41829. Uniform: 'uniform',
  41830. Storage: 'storage',
  41831. ReadOnlyStorage: 'read-only-storage'
  41832. };
  41833. const GPUStorageTextureAccess = {
  41834. WriteOnly: 'write-only',
  41835. ReadOnly: 'read-only',
  41836. ReadWrite: 'read-write',
  41837. };
  41838. const GPUTextureSampleType = {
  41839. Float: 'float',
  41840. UnfilterableFloat: 'unfilterable-float',
  41841. Depth: 'depth',
  41842. SInt: 'sint',
  41843. UInt: 'uint'
  41844. };
  41845. const GPUTextureDimension = {
  41846. OneD: '1d',
  41847. TwoD: '2d',
  41848. ThreeD: '3d'
  41849. };
  41850. const GPUTextureViewDimension = {
  41851. OneD: '1d',
  41852. TwoD: '2d',
  41853. TwoDArray: '2d-array',
  41854. Cube: 'cube',
  41855. CubeArray: 'cube-array',
  41856. ThreeD: '3d'
  41857. };
  41858. const GPUTextureAspect = {
  41859. All: 'all',
  41860. StencilOnly: 'stencil-only',
  41861. DepthOnly: 'depth-only'
  41862. };
  41863. const GPUInputStepMode = {
  41864. Vertex: 'vertex',
  41865. Instance: 'instance'
  41866. };
  41867. const GPUFeatureName = {
  41868. DepthClipControl: 'depth-clip-control',
  41869. Depth32FloatStencil8: 'depth32float-stencil8',
  41870. TextureCompressionBC: 'texture-compression-bc',
  41871. TextureCompressionETC2: 'texture-compression-etc2',
  41872. TextureCompressionASTC: 'texture-compression-astc',
  41873. TimestampQuery: 'timestamp-query',
  41874. IndirectFirstInstance: 'indirect-first-instance',
  41875. ShaderF16: 'shader-f16',
  41876. RG11B10UFloat: 'rg11b10ufloat-renderable',
  41877. BGRA8UNormStorage: 'bgra8unorm-storage',
  41878. Float32Filterable: 'float32-filterable',
  41879. ClipDistances: 'clip-distances',
  41880. DualSourceBlending: 'dual-source-blending',
  41881. Subgroups: 'subgroups'
  41882. };
  41883. /**
  41884. * Represents a sampler binding type.
  41885. *
  41886. * @private
  41887. * @augments Binding
  41888. */
  41889. class Sampler extends Binding {
  41890. /**
  41891. * Constructs a new sampler.
  41892. *
  41893. * @param {String} name - The samplers's name.
  41894. * @param {Texture?} texture - The texture this binding is referring to.
  41895. */
  41896. constructor( name, texture ) {
  41897. super( name );
  41898. /**
  41899. * The texture the sampler is referring to.
  41900. *
  41901. * @type {Texture?}
  41902. */
  41903. this.texture = texture;
  41904. /**
  41905. * The binding's version.
  41906. *
  41907. * @type {Number}
  41908. */
  41909. this.version = texture ? texture.version : 0;
  41910. /**
  41911. * This flag can be used for type testing.
  41912. *
  41913. * @type {Boolean}
  41914. * @readonly
  41915. * @default true
  41916. */
  41917. this.isSampler = true;
  41918. }
  41919. }
  41920. /**
  41921. * A special form of sampler binding type.
  41922. * It's texture value is managed by a node object.
  41923. *
  41924. * @private
  41925. * @augments Sampler
  41926. */
  41927. class NodeSampler extends Sampler {
  41928. /**
  41929. * Constructs a new node-based sampler.
  41930. *
  41931. * @param {String} name - The samplers's name.
  41932. * @param {TextureNode} textureNode - The texture node.
  41933. * @param {UniformGroupNode} groupNode - The uniform group node.
  41934. */
  41935. constructor( name, textureNode, groupNode ) {
  41936. super( name, textureNode ? textureNode.value : null );
  41937. /**
  41938. * The texture node.
  41939. *
  41940. * @type {TextureNode}
  41941. */
  41942. this.textureNode = textureNode;
  41943. /**
  41944. * The uniform group node.
  41945. *
  41946. * @type {UniformGroupNode}
  41947. */
  41948. this.groupNode = groupNode;
  41949. }
  41950. /**
  41951. * Updates the texture value of this sampler.
  41952. */
  41953. update() {
  41954. this.texture = this.textureNode.value;
  41955. }
  41956. }
  41957. /**
  41958. * Represents a storage buffer binding type.
  41959. *
  41960. * @private
  41961. * @augments Buffer
  41962. */
  41963. class StorageBuffer extends Buffer {
  41964. /**
  41965. * Constructs a new uniform buffer.
  41966. *
  41967. * @param {String} name - The buffer's name.
  41968. * @param {BufferAttribute} attribute - The buffer attribute.
  41969. */
  41970. constructor( name, attribute ) {
  41971. super( name, attribute ? attribute.array : null );
  41972. /**
  41973. * This flag can be used for type testing.
  41974. *
  41975. * @type {BufferAttribute}
  41976. */
  41977. this.attribute = attribute;
  41978. /**
  41979. * This flag can be used for type testing.
  41980. *
  41981. * @type {Boolean}
  41982. * @readonly
  41983. * @default true
  41984. */
  41985. this.isStorageBuffer = true;
  41986. }
  41987. }
  41988. let _id = 0;
  41989. /**
  41990. * A special form of storage buffer binding type.
  41991. * It's buffer value is managed by a node object.
  41992. *
  41993. * @private
  41994. * @augments StorageBuffer
  41995. */
  41996. class NodeStorageBuffer extends StorageBuffer {
  41997. /**
  41998. * Constructs a new node-based storage buffer.
  41999. *
  42000. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  42001. * @param {UniformGroupNode} groupNode - The uniform group node.
  42002. */
  42003. constructor( nodeUniform, groupNode ) {
  42004. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42005. /**
  42006. * The node uniform.
  42007. *
  42008. * @type {StorageBufferNode}
  42009. */
  42010. this.nodeUniform = nodeUniform;
  42011. /**
  42012. * The access type.
  42013. *
  42014. * @type {String}
  42015. */
  42016. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  42017. /**
  42018. * The uniform group node.
  42019. *
  42020. * @type {UniformGroupNode}
  42021. */
  42022. this.groupNode = groupNode;
  42023. }
  42024. /**
  42025. * The storage buffer.
  42026. *
  42027. * @type {BufferAttribute}
  42028. */
  42029. get buffer() {
  42030. return this.nodeUniform.value;
  42031. }
  42032. }
  42033. /**
  42034. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  42035. *
  42036. * @private
  42037. */
  42038. class WebGPUTexturePassUtils extends DataMap {
  42039. /**
  42040. * Constructs a new utility object.
  42041. *
  42042. * @param {GPUDevice} device - The WebGPU device.
  42043. */
  42044. constructor( device ) {
  42045. super();
  42046. /**
  42047. * The WebGPU device.
  42048. *
  42049. * @type {GPUDevice}
  42050. */
  42051. this.device = device;
  42052. const mipmapVertexSource = `
  42053. struct VarysStruct {
  42054. @builtin( position ) Position: vec4<f32>,
  42055. @location( 0 ) vTex : vec2<f32>
  42056. };
  42057. @vertex
  42058. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42059. var Varys : VarysStruct;
  42060. var pos = array< vec2<f32>, 4 >(
  42061. vec2<f32>( -1.0, 1.0 ),
  42062. vec2<f32>( 1.0, 1.0 ),
  42063. vec2<f32>( -1.0, -1.0 ),
  42064. vec2<f32>( 1.0, -1.0 )
  42065. );
  42066. var tex = array< vec2<f32>, 4 >(
  42067. vec2<f32>( 0.0, 0.0 ),
  42068. vec2<f32>( 1.0, 0.0 ),
  42069. vec2<f32>( 0.0, 1.0 ),
  42070. vec2<f32>( 1.0, 1.0 )
  42071. );
  42072. Varys.vTex = tex[ vertexIndex ];
  42073. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42074. return Varys;
  42075. }
  42076. `;
  42077. const mipmapFragmentSource = `
  42078. @group( 0 ) @binding( 0 )
  42079. var imgSampler : sampler;
  42080. @group( 0 ) @binding( 1 )
  42081. var img : texture_2d<f32>;
  42082. @fragment
  42083. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42084. return textureSample( img, imgSampler, vTex );
  42085. }
  42086. `;
  42087. const flipYFragmentSource = `
  42088. @group( 0 ) @binding( 0 )
  42089. var imgSampler : sampler;
  42090. @group( 0 ) @binding( 1 )
  42091. var img : texture_2d<f32>;
  42092. @fragment
  42093. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42094. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42095. }
  42096. `;
  42097. /**
  42098. * The mipmap GPU sampler.
  42099. *
  42100. * @type {GPUSampler}
  42101. */
  42102. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42103. /**
  42104. * The flipY GPU sampler.
  42105. *
  42106. * @type {GPUSampler}
  42107. */
  42108. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42109. /**
  42110. * A cache for GPU render pipelines used for copy/transfer passes.
  42111. * Every texture format requires a unique pipeline.
  42112. *
  42113. * @type {Object<String,GPURenderPipeline>}
  42114. */
  42115. this.transferPipelines = {};
  42116. /**
  42117. * A cache for GPU render pipelines used for flipY passes.
  42118. * Every texture format requires a unique pipeline.
  42119. *
  42120. * @type {Object<String,GPURenderPipeline>}
  42121. */
  42122. this.flipYPipelines = {};
  42123. /**
  42124. * The mipmap vertex shader module.
  42125. *
  42126. * @type {GPUShaderModule}
  42127. */
  42128. this.mipmapVertexShaderModule = device.createShaderModule( {
  42129. label: 'mipmapVertex',
  42130. code: mipmapVertexSource
  42131. } );
  42132. /**
  42133. * The mipmap fragment shader module.
  42134. *
  42135. * @type {GPUShaderModule}
  42136. */
  42137. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42138. label: 'mipmapFragment',
  42139. code: mipmapFragmentSource
  42140. } );
  42141. /**
  42142. * The flipY fragment shader module.
  42143. *
  42144. * @type {GPUShaderModule}
  42145. */
  42146. this.flipYFragmentShaderModule = device.createShaderModule( {
  42147. label: 'flipYFragment',
  42148. code: flipYFragmentSource
  42149. } );
  42150. }
  42151. /**
  42152. * Returns a render pipeline for the internal copy render pass. The pass
  42153. * requires a unique render pipeline for each texture format.
  42154. *
  42155. * @param {String} format - The GPU texture format
  42156. * @return {GPURenderPipeline} The GPU render pipeline.
  42157. */
  42158. getTransferPipeline( format ) {
  42159. let pipeline = this.transferPipelines[ format ];
  42160. if ( pipeline === undefined ) {
  42161. pipeline = this.device.createRenderPipeline( {
  42162. label: `mipmap-${ format }`,
  42163. vertex: {
  42164. module: this.mipmapVertexShaderModule,
  42165. entryPoint: 'main'
  42166. },
  42167. fragment: {
  42168. module: this.mipmapFragmentShaderModule,
  42169. entryPoint: 'main',
  42170. targets: [ { format } ]
  42171. },
  42172. primitive: {
  42173. topology: GPUPrimitiveTopology.TriangleStrip,
  42174. stripIndexFormat: GPUIndexFormat.Uint32
  42175. },
  42176. layout: 'auto'
  42177. } );
  42178. this.transferPipelines[ format ] = pipeline;
  42179. }
  42180. return pipeline;
  42181. }
  42182. /**
  42183. * Returns a render pipeline for the flipY render pass. The pass
  42184. * requires a unique render pipeline for each texture format.
  42185. *
  42186. * @param {String} format - The GPU texture format
  42187. * @return {GPURenderPipeline} The GPU render pipeline.
  42188. */
  42189. getFlipYPipeline( format ) {
  42190. let pipeline = this.flipYPipelines[ format ];
  42191. if ( pipeline === undefined ) {
  42192. pipeline = this.device.createRenderPipeline( {
  42193. label: `flipY-${ format }`,
  42194. vertex: {
  42195. module: this.mipmapVertexShaderModule,
  42196. entryPoint: 'main'
  42197. },
  42198. fragment: {
  42199. module: this.flipYFragmentShaderModule,
  42200. entryPoint: 'main',
  42201. targets: [ { format } ]
  42202. },
  42203. primitive: {
  42204. topology: GPUPrimitiveTopology.TriangleStrip,
  42205. stripIndexFormat: GPUIndexFormat.Uint32
  42206. },
  42207. layout: 'auto'
  42208. } );
  42209. this.flipYPipelines[ format ] = pipeline;
  42210. }
  42211. return pipeline;
  42212. }
  42213. /**
  42214. * Flip the contents of the given GPU texture along its vertical axis.
  42215. *
  42216. * @param {GPUTexture} textureGPU - The GPU texture object.
  42217. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42218. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42219. */
  42220. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42221. const format = textureGPUDescriptor.format;
  42222. const { width, height } = textureGPUDescriptor.size;
  42223. const transferPipeline = this.getTransferPipeline( format );
  42224. const flipYPipeline = this.getFlipYPipeline( format );
  42225. const tempTexture = this.device.createTexture( {
  42226. size: { width, height, depthOrArrayLayers: 1 },
  42227. format,
  42228. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42229. } );
  42230. const srcView = textureGPU.createView( {
  42231. baseMipLevel: 0,
  42232. mipLevelCount: 1,
  42233. dimension: GPUTextureViewDimension.TwoD,
  42234. baseArrayLayer
  42235. } );
  42236. const dstView = tempTexture.createView( {
  42237. baseMipLevel: 0,
  42238. mipLevelCount: 1,
  42239. dimension: GPUTextureViewDimension.TwoD,
  42240. baseArrayLayer: 0
  42241. } );
  42242. const commandEncoder = this.device.createCommandEncoder( {} );
  42243. const pass = ( pipeline, sourceView, destinationView ) => {
  42244. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42245. const bindGroup = this.device.createBindGroup( {
  42246. layout: bindGroupLayout,
  42247. entries: [ {
  42248. binding: 0,
  42249. resource: this.flipYSampler
  42250. }, {
  42251. binding: 1,
  42252. resource: sourceView
  42253. } ]
  42254. } );
  42255. const passEncoder = commandEncoder.beginRenderPass( {
  42256. colorAttachments: [ {
  42257. view: destinationView,
  42258. loadOp: GPULoadOp.Clear,
  42259. storeOp: GPUStoreOp.Store,
  42260. clearValue: [ 0, 0, 0, 0 ]
  42261. } ]
  42262. } );
  42263. passEncoder.setPipeline( pipeline );
  42264. passEncoder.setBindGroup( 0, bindGroup );
  42265. passEncoder.draw( 4, 1, 0, 0 );
  42266. passEncoder.end();
  42267. };
  42268. pass( transferPipeline, srcView, dstView );
  42269. pass( flipYPipeline, dstView, srcView );
  42270. this.device.queue.submit( [ commandEncoder.finish() ] );
  42271. tempTexture.destroy();
  42272. }
  42273. /**
  42274. * Generates mipmaps for the given GPU texture.
  42275. *
  42276. * @param {GPUTexture} textureGPU - The GPU texture object.
  42277. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42278. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42279. */
  42280. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42281. const textureData = this.get( textureGPU );
  42282. if ( textureData.useCount === undefined ) {
  42283. textureData.useCount = 0;
  42284. textureData.layers = [];
  42285. }
  42286. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42287. const commandEncoder = this.device.createCommandEncoder( {} );
  42288. this._mipmapRunBundles( commandEncoder, passes );
  42289. this.device.queue.submit( [ commandEncoder.finish() ] );
  42290. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42291. textureData.useCount ++;
  42292. }
  42293. /**
  42294. * Since multiple copy render passes are required to generate mipmaps, the passes
  42295. * are managed as render bundles to improve performance.
  42296. *
  42297. * @param {GPUTexture} textureGPU - The GPU texture object.
  42298. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42299. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  42300. * @return {Array} An array of render bundles.
  42301. */
  42302. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42303. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42304. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42305. let srcView = textureGPU.createView( {
  42306. baseMipLevel: 0,
  42307. mipLevelCount: 1,
  42308. dimension: GPUTextureViewDimension.TwoD,
  42309. baseArrayLayer
  42310. } );
  42311. const passes = [];
  42312. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42313. const bindGroup = this.device.createBindGroup( {
  42314. layout: bindGroupLayout,
  42315. entries: [ {
  42316. binding: 0,
  42317. resource: this.mipmapSampler
  42318. }, {
  42319. binding: 1,
  42320. resource: srcView
  42321. } ]
  42322. } );
  42323. const dstView = textureGPU.createView( {
  42324. baseMipLevel: i,
  42325. mipLevelCount: 1,
  42326. dimension: GPUTextureViewDimension.TwoD,
  42327. baseArrayLayer
  42328. } );
  42329. const passDescriptor = {
  42330. colorAttachments: [ {
  42331. view: dstView,
  42332. loadOp: GPULoadOp.Clear,
  42333. storeOp: GPUStoreOp.Store,
  42334. clearValue: [ 0, 0, 0, 0 ]
  42335. } ]
  42336. };
  42337. const passEncoder = this.device.createRenderBundleEncoder( {
  42338. colorFormats: [ textureGPUDescriptor.format ]
  42339. } );
  42340. passEncoder.setPipeline( pipeline );
  42341. passEncoder.setBindGroup( 0, bindGroup );
  42342. passEncoder.draw( 4, 1, 0, 0 );
  42343. passes.push( {
  42344. renderBundles: [ passEncoder.finish() ],
  42345. passDescriptor
  42346. } );
  42347. srcView = dstView;
  42348. }
  42349. return passes;
  42350. }
  42351. /**
  42352. * Executes the render bundles.
  42353. *
  42354. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  42355. * @param {Array} passes - An array of render bundles.
  42356. */
  42357. _mipmapRunBundles( commandEncoder, passes ) {
  42358. const levels = passes.length;
  42359. for ( let i = 0; i < levels; i ++ ) {
  42360. const pass = passes[ i ];
  42361. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42362. passEncoder.executeBundles( pass.renderBundles );
  42363. passEncoder.end();
  42364. }
  42365. }
  42366. }
  42367. const _compareToWebGPU = {
  42368. [ NeverCompare ]: 'never',
  42369. [ LessCompare ]: 'less',
  42370. [ EqualCompare ]: 'equal',
  42371. [ LessEqualCompare ]: 'less-equal',
  42372. [ GreaterCompare ]: 'greater',
  42373. [ GreaterEqualCompare ]: 'greater-equal',
  42374. [ AlwaysCompare ]: 'always',
  42375. [ NotEqualCompare ]: 'not-equal'
  42376. };
  42377. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42378. /**
  42379. * A WebGPU backend utility module for managing textures.
  42380. *
  42381. * @private
  42382. */
  42383. class WebGPUTextureUtils {
  42384. /**
  42385. * Constructs a new utility object.
  42386. *
  42387. * @param {WebGPUBackend} backend - The WebGPU backend.
  42388. */
  42389. constructor( backend ) {
  42390. /**
  42391. * A reference to the WebGPU backend.
  42392. *
  42393. * @type {WebGPUBackend}
  42394. */
  42395. this.backend = backend;
  42396. /**
  42397. * A reference to the pass utils.
  42398. *
  42399. * @type {WebGPUTexturePassUtils?}
  42400. * @default null
  42401. */
  42402. this._passUtils = null;
  42403. /**
  42404. * A dictionary for managing default textures. The key
  42405. * is the texture format, the value the texture object.
  42406. *
  42407. * @type {Object<String,Texture>}
  42408. */
  42409. this.defaultTexture = {};
  42410. /**
  42411. * A dictionary for managing default cube textures. The key
  42412. * is the texture format, the value the texture object.
  42413. *
  42414. * @type {Object<String,CubeTexture>}
  42415. */
  42416. this.defaultCubeTexture = {};
  42417. /**
  42418. * A default video frame.
  42419. *
  42420. * @type {VideoFrame?}
  42421. * @default null
  42422. */
  42423. this.defaultVideoFrame = null;
  42424. /**
  42425. * Represents the color attachment of the default framebuffer.
  42426. *
  42427. * @type {GPUTexture?}
  42428. * @default null
  42429. */
  42430. this.colorBuffer = null;
  42431. /**
  42432. * Represents the depth attachment of the default framebuffer.
  42433. *
  42434. * @type {DepthTexture}
  42435. */
  42436. this.depthTexture = new DepthTexture();
  42437. this.depthTexture.name = 'depthBuffer';
  42438. }
  42439. /**
  42440. * Creates a GPU sampler for the given texture.
  42441. *
  42442. * @param {Texture} texture - The texture to create the sampler for.
  42443. */
  42444. createSampler( texture ) {
  42445. const backend = this.backend;
  42446. const device = backend.device;
  42447. const textureGPU = backend.get( texture );
  42448. const samplerDescriptorGPU = {
  42449. addressModeU: this._convertAddressMode( texture.wrapS ),
  42450. addressModeV: this._convertAddressMode( texture.wrapT ),
  42451. addressModeW: this._convertAddressMode( texture.wrapR ),
  42452. magFilter: this._convertFilterMode( texture.magFilter ),
  42453. minFilter: this._convertFilterMode( texture.minFilter ),
  42454. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42455. maxAnisotropy: 1
  42456. };
  42457. // anisotropy can only be used when all filter modes are set to linear.
  42458. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42459. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42460. }
  42461. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42462. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42463. }
  42464. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42465. }
  42466. /**
  42467. * Creates a default texture for the given texture that can be used
  42468. * as a placeholder until the actual texture is ready for usage.
  42469. *
  42470. * @param {Texture} texture - The texture to create a default texture for.
  42471. */
  42472. createDefaultTexture( texture ) {
  42473. let textureGPU;
  42474. const format = getFormat( texture );
  42475. if ( texture.isCubeTexture ) {
  42476. textureGPU = this._getDefaultCubeTextureGPU( format );
  42477. } else if ( texture.isVideoTexture ) {
  42478. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42479. } else {
  42480. textureGPU = this._getDefaultTextureGPU( format );
  42481. }
  42482. this.backend.get( texture ).texture = textureGPU;
  42483. }
  42484. /**
  42485. * Defines a texture on the GPU for the given texture object.
  42486. *
  42487. * @param {Texture} texture - The texture.
  42488. * @param {Object} [options={}] - Optional configuration parameter.
  42489. * @return {undefined}
  42490. */
  42491. createTexture( texture, options = {} ) {
  42492. const backend = this.backend;
  42493. const textureData = backend.get( texture );
  42494. if ( textureData.initialized ) {
  42495. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42496. }
  42497. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42498. if ( options.levels === undefined ) options.levels = 1;
  42499. if ( options.depth === undefined ) options.depth = 1;
  42500. const { width, height, depth, levels } = options;
  42501. if ( texture.isFramebufferTexture ) {
  42502. if ( options.renderTarget ) {
  42503. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42504. } else {
  42505. options.format = this.backend.utils.getPreferredCanvasFormat();
  42506. }
  42507. }
  42508. const dimension = this._getDimension( texture );
  42509. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42510. textureData.format = format;
  42511. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  42512. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42513. if ( texture.isStorageTexture === true ) {
  42514. usage |= GPUTextureUsage.STORAGE_BINDING;
  42515. }
  42516. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42517. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42518. }
  42519. const textureDescriptorGPU = {
  42520. label: texture.name,
  42521. size: {
  42522. width: width,
  42523. height: height,
  42524. depthOrArrayLayers: depth,
  42525. },
  42526. mipLevelCount: levels,
  42527. sampleCount: primarySamples,
  42528. dimension: dimension,
  42529. format: format,
  42530. usage: usage
  42531. };
  42532. // texture creation
  42533. if ( texture.isVideoTexture ) {
  42534. const video = texture.source.data;
  42535. const videoFrame = new VideoFrame( video );
  42536. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42537. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42538. videoFrame.close();
  42539. textureData.externalTexture = video;
  42540. } else {
  42541. if ( format === undefined ) {
  42542. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42543. return this.createDefaultTexture( texture );
  42544. }
  42545. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42546. }
  42547. if ( isMSAA ) {
  42548. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42549. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42550. msaaTextureDescriptorGPU.sampleCount = samples;
  42551. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42552. }
  42553. textureData.initialized = true;
  42554. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42555. }
  42556. /**
  42557. * Destroys the GPU data for the given texture object.
  42558. *
  42559. * @param {Texture} texture - The texture.
  42560. */
  42561. destroyTexture( texture ) {
  42562. const backend = this.backend;
  42563. const textureData = backend.get( texture );
  42564. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  42565. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42566. backend.delete( texture );
  42567. }
  42568. /**
  42569. * Destroys the GPU sampler for the given texture.
  42570. *
  42571. * @param {Texture} texture - The texture to destroy the sampler for.
  42572. */
  42573. destroySampler( texture ) {
  42574. const backend = this.backend;
  42575. const textureData = backend.get( texture );
  42576. delete textureData.sampler;
  42577. }
  42578. /**
  42579. * Generates mipmaps for the given texture.
  42580. *
  42581. * @param {Texture} texture - The texture.
  42582. */
  42583. generateMipmaps( texture ) {
  42584. const textureData = this.backend.get( texture );
  42585. if ( texture.isCubeTexture ) {
  42586. for ( let i = 0; i < 6; i ++ ) {
  42587. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42588. }
  42589. } else {
  42590. const depth = texture.image.depth || 1;
  42591. for ( let i = 0; i < depth; i ++ ) {
  42592. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42593. }
  42594. }
  42595. }
  42596. /**
  42597. * Returns the color buffer representing the color
  42598. * attachment of the default framebuffer.
  42599. *
  42600. * @return {GPUTexture} The color buffer.
  42601. */
  42602. getColorBuffer() {
  42603. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42604. const backend = this.backend;
  42605. const { width, height } = backend.getDrawingBufferSize();
  42606. this.colorBuffer = backend.device.createTexture( {
  42607. label: 'colorBuffer',
  42608. size: {
  42609. width: width,
  42610. height: height,
  42611. depthOrArrayLayers: 1
  42612. },
  42613. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42614. format: backend.utils.getPreferredCanvasFormat(),
  42615. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42616. } );
  42617. return this.colorBuffer;
  42618. }
  42619. /**
  42620. * Returns the depth buffer representing the depth
  42621. * attachment of the default framebuffer.
  42622. *
  42623. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  42624. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  42625. * @return {GPUTexture} The depth buffer.
  42626. */
  42627. getDepthBuffer( depth = true, stencil = false ) {
  42628. const backend = this.backend;
  42629. const { width, height } = backend.getDrawingBufferSize();
  42630. const depthTexture = this.depthTexture;
  42631. const depthTextureGPU = backend.get( depthTexture ).texture;
  42632. let format, type;
  42633. if ( stencil ) {
  42634. format = DepthStencilFormat;
  42635. type = UnsignedInt248Type;
  42636. } else if ( depth ) {
  42637. format = DepthFormat;
  42638. type = UnsignedIntType;
  42639. }
  42640. if ( depthTextureGPU !== undefined ) {
  42641. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42642. return depthTextureGPU;
  42643. }
  42644. this.destroyTexture( depthTexture );
  42645. }
  42646. depthTexture.name = 'depthBuffer';
  42647. depthTexture.format = format;
  42648. depthTexture.type = type;
  42649. depthTexture.image.width = width;
  42650. depthTexture.image.height = height;
  42651. this.createTexture( depthTexture, { width, height } );
  42652. return backend.get( depthTexture ).texture;
  42653. }
  42654. /**
  42655. * Uploads the updated texture data to the GPU.
  42656. *
  42657. * @param {Texture} texture - The texture.
  42658. * @param {Object} [options={}] - Optional configuration parameter.
  42659. */
  42660. updateTexture( texture, options ) {
  42661. const textureData = this.backend.get( texture );
  42662. const { textureDescriptorGPU } = textureData;
  42663. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42664. return;
  42665. // transfer texture data
  42666. if ( texture.isDataTexture ) {
  42667. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42668. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42669. for ( let i = 0; i < options.image.depth; i ++ ) {
  42670. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42671. }
  42672. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42673. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42674. } else if ( texture.isCubeTexture ) {
  42675. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42676. } else if ( texture.isVideoTexture ) {
  42677. const video = texture.source.data;
  42678. textureData.externalTexture = video;
  42679. } else {
  42680. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42681. }
  42682. //
  42683. textureData.version = texture.version;
  42684. if ( texture.onUpdate ) texture.onUpdate( texture );
  42685. }
  42686. /**
  42687. * Returns texture data as a typed array.
  42688. *
  42689. * @async
  42690. * @param {Texture} texture - The texture to copy.
  42691. * @param {Number} x - The x coordinate of the copy origin.
  42692. * @param {Number} y - The y coordinate of the copy origin.
  42693. * @param {Number} width - The width of the copy.
  42694. * @param {Number} height - The height of the copy.
  42695. * @param {Number} faceIndex - The face index.
  42696. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42697. */
  42698. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42699. const device = this.backend.device;
  42700. const textureData = this.backend.get( texture );
  42701. const textureGPU = textureData.texture;
  42702. const format = textureData.textureDescriptorGPU.format;
  42703. const bytesPerTexel = this._getBytesPerTexel( format );
  42704. let bytesPerRow = width * bytesPerTexel;
  42705. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42706. const readBuffer = device.createBuffer(
  42707. {
  42708. size: width * height * bytesPerTexel,
  42709. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42710. }
  42711. );
  42712. const encoder = device.createCommandEncoder();
  42713. encoder.copyTextureToBuffer(
  42714. {
  42715. texture: textureGPU,
  42716. origin: { x, y, z: faceIndex },
  42717. },
  42718. {
  42719. buffer: readBuffer,
  42720. bytesPerRow: bytesPerRow
  42721. },
  42722. {
  42723. width: width,
  42724. height: height
  42725. }
  42726. );
  42727. const typedArrayType = this._getTypedArrayType( format );
  42728. device.queue.submit( [ encoder.finish() ] );
  42729. await readBuffer.mapAsync( GPUMapMode.READ );
  42730. const buffer = readBuffer.getMappedRange();
  42731. return new typedArrayType( buffer );
  42732. }
  42733. /**
  42734. * Returns `true` if the given texture is an environment map.
  42735. *
  42736. * @private
  42737. * @param {Texture} texture - The texture.
  42738. * @return {Boolean} Whether the given texture is an environment map or not.
  42739. */
  42740. _isEnvironmentTexture( texture ) {
  42741. const mapping = texture.mapping;
  42742. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42743. }
  42744. /**
  42745. * Returns the default GPU texture for the given format.
  42746. *
  42747. * @private
  42748. * @param {String} format - The GPU format.
  42749. * @return {GPUTexture} The GPU texture.
  42750. */
  42751. _getDefaultTextureGPU( format ) {
  42752. let defaultTexture = this.defaultTexture[ format ];
  42753. if ( defaultTexture === undefined ) {
  42754. const texture = new Texture();
  42755. texture.minFilter = NearestFilter;
  42756. texture.magFilter = NearestFilter;
  42757. this.createTexture( texture, { width: 1, height: 1, format } );
  42758. this.defaultTexture[ format ] = defaultTexture = texture;
  42759. }
  42760. return this.backend.get( defaultTexture ).texture;
  42761. }
  42762. /**
  42763. * Returns the default GPU cube texture for the given format.
  42764. *
  42765. * @private
  42766. * @param {String} format - The GPU format.
  42767. * @return {GPUTexture} The GPU texture.
  42768. */
  42769. _getDefaultCubeTextureGPU( format ) {
  42770. let defaultCubeTexture = this.defaultTexture[ format ];
  42771. if ( defaultCubeTexture === undefined ) {
  42772. const texture = new CubeTexture();
  42773. texture.minFilter = NearestFilter;
  42774. texture.magFilter = NearestFilter;
  42775. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42776. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42777. }
  42778. return this.backend.get( defaultCubeTexture ).texture;
  42779. }
  42780. /**
  42781. * Returns the default video frame used as default data in context of video textures.
  42782. *
  42783. * @private
  42784. * @return {VideoFrame} The video frame.
  42785. */
  42786. _getDefaultVideoFrame() {
  42787. let defaultVideoFrame = this.defaultVideoFrame;
  42788. if ( defaultVideoFrame === null ) {
  42789. const init = {
  42790. timestamp: 0,
  42791. codedWidth: 1,
  42792. codedHeight: 1,
  42793. format: 'RGBA',
  42794. };
  42795. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42796. }
  42797. return defaultVideoFrame;
  42798. }
  42799. /**
  42800. * Uploads cube texture image data to the GPU memory.
  42801. *
  42802. * @private
  42803. * @param {Array} images - The cube image data.
  42804. * @param {GPUTexture} textureGPU - The GPU texture.
  42805. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42806. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42807. */
  42808. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42809. for ( let i = 0; i < 6; i ++ ) {
  42810. const image = images[ i ];
  42811. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42812. if ( image.isDataTexture ) {
  42813. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42814. } else {
  42815. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42816. }
  42817. }
  42818. }
  42819. /**
  42820. * Uploads texture image data to the GPU memory.
  42821. *
  42822. * @private
  42823. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  42824. * @param {GPUTexture} textureGPU - The GPU texture.
  42825. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42826. * @param {Number} originDepth - The origin depth.
  42827. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42828. */
  42829. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42830. const device = this.backend.device;
  42831. device.queue.copyExternalImageToTexture(
  42832. {
  42833. source: image,
  42834. flipY: flipY
  42835. }, {
  42836. texture: textureGPU,
  42837. mipLevel: 0,
  42838. origin: { x: 0, y: 0, z: originDepth }
  42839. }, {
  42840. width: image.width,
  42841. height: image.height,
  42842. depthOrArrayLayers: 1
  42843. }
  42844. );
  42845. }
  42846. /**
  42847. * Returns the pass utils singleton.
  42848. *
  42849. * @private
  42850. * @return {WebGPUTexturePassUtils} The utils instance.
  42851. */
  42852. _getPassUtils() {
  42853. let passUtils = this._passUtils;
  42854. if ( passUtils === null ) {
  42855. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42856. }
  42857. return passUtils;
  42858. }
  42859. /**
  42860. * Generates mipmaps for the given GPU texture.
  42861. *
  42862. * @private
  42863. * @param {GPUTexture} textureGPU - The GPU texture object.
  42864. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42865. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42866. */
  42867. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42868. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42869. }
  42870. /**
  42871. * Flip the contents of the given GPU texture along its vertical axis.
  42872. *
  42873. * @private
  42874. * @param {GPUTexture} textureGPU - The GPU texture object.
  42875. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42876. * @param {Number} [originDepth=0] - The origin depth.
  42877. */
  42878. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42879. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42880. }
  42881. /**
  42882. * Uploads texture buffer data to the GPU memory.
  42883. *
  42884. * @private
  42885. * @param {Object} image - An object defining the image buffer data.
  42886. * @param {GPUTexture} textureGPU - The GPU texture.
  42887. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42888. * @param {Number} originDepth - The origin depth.
  42889. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42890. * @param {Number} [depth=0] - TODO.
  42891. */
  42892. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42893. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42894. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42895. const device = this.backend.device;
  42896. const data = image.data;
  42897. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42898. const bytesPerRow = image.width * bytesPerTexel;
  42899. device.queue.writeTexture(
  42900. {
  42901. texture: textureGPU,
  42902. mipLevel: 0,
  42903. origin: { x: 0, y: 0, z: originDepth }
  42904. },
  42905. data,
  42906. {
  42907. offset: image.width * image.height * bytesPerTexel * depth,
  42908. bytesPerRow
  42909. },
  42910. {
  42911. width: image.width,
  42912. height: image.height,
  42913. depthOrArrayLayers: 1
  42914. } );
  42915. if ( flipY === true ) {
  42916. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42917. }
  42918. }
  42919. /**
  42920. * Uploads compressed texture data to the GPU memory.
  42921. *
  42922. * @private
  42923. * @param {Array<Object>} mipmaps - An array with mipmap data.
  42924. * @param {GPUTexture} textureGPU - The GPU texture.
  42925. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42926. */
  42927. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42928. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42929. const device = this.backend.device;
  42930. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42931. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42932. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42933. const mipmap = mipmaps[ i ];
  42934. const width = mipmap.width;
  42935. const height = mipmap.height;
  42936. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42937. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42938. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42939. for ( let j = 0; j < depth; j ++ ) {
  42940. device.queue.writeTexture(
  42941. {
  42942. texture: textureGPU,
  42943. mipLevel: i,
  42944. origin: { x: 0, y: 0, z: j }
  42945. },
  42946. mipmap.data,
  42947. {
  42948. offset: j * bytesPerImage,
  42949. bytesPerRow,
  42950. rowsPerImage: Math.ceil( height / blockData.height )
  42951. },
  42952. {
  42953. width: Math.ceil( width / blockData.width ) * blockData.width,
  42954. height: Math.ceil( height / blockData.height ) * blockData.height,
  42955. depthOrArrayLayers: 1
  42956. }
  42957. );
  42958. }
  42959. }
  42960. }
  42961. /**
  42962. * This method is only relevant for compressed texture formats. It returns a block
  42963. * data descriptor for the given GPU compressed texture format.
  42964. *
  42965. * @private
  42966. * @param {String} format - The GPU compressed texture format.
  42967. * @return {Object} The block data descriptor.
  42968. */
  42969. _getBlockData( format ) {
  42970. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42971. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42972. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42973. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42974. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42975. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42976. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42977. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42978. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42979. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42980. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42981. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42982. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42983. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42984. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42985. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42986. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42987. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42988. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42989. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42990. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42991. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42992. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42993. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42994. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42995. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42996. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42997. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42998. }
  42999. /**
  43000. * Converts the three.js uv wrapping constants to GPU address mode constants.
  43001. *
  43002. * @private
  43003. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  43004. * @return {String} The GPU address mode.
  43005. */
  43006. _convertAddressMode( value ) {
  43007. let addressMode = GPUAddressMode.ClampToEdge;
  43008. if ( value === RepeatWrapping ) {
  43009. addressMode = GPUAddressMode.Repeat;
  43010. } else if ( value === MirroredRepeatWrapping ) {
  43011. addressMode = GPUAddressMode.MirrorRepeat;
  43012. }
  43013. return addressMode;
  43014. }
  43015. /**
  43016. * Converts the three.js filter constants to GPU filter constants.
  43017. *
  43018. * @private
  43019. * @param {Number} value - The three.js constant defining a filter mode.
  43020. * @return {String} The GPU filter mode.
  43021. */
  43022. _convertFilterMode( value ) {
  43023. let filterMode = GPUFilterMode.Linear;
  43024. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43025. filterMode = GPUFilterMode.Nearest;
  43026. }
  43027. return filterMode;
  43028. }
  43029. /**
  43030. * Returns the bytes-per-texel value for the given GPU texture format.
  43031. *
  43032. * @private
  43033. * @param {String} format - The GPU texture format.
  43034. * @return {Number} The bytes-per-texel.
  43035. */
  43036. _getBytesPerTexel( format ) {
  43037. // 8-bit formats
  43038. if ( format === GPUTextureFormat.R8Unorm ||
  43039. format === GPUTextureFormat.R8Snorm ||
  43040. format === GPUTextureFormat.R8Uint ||
  43041. format === GPUTextureFormat.R8Sint ) return 1;
  43042. // 16-bit formats
  43043. if ( format === GPUTextureFormat.R16Uint ||
  43044. format === GPUTextureFormat.R16Sint ||
  43045. format === GPUTextureFormat.R16Float ||
  43046. format === GPUTextureFormat.RG8Unorm ||
  43047. format === GPUTextureFormat.RG8Snorm ||
  43048. format === GPUTextureFormat.RG8Uint ||
  43049. format === GPUTextureFormat.RG8Sint ) return 2;
  43050. // 32-bit formats
  43051. if ( format === GPUTextureFormat.R32Uint ||
  43052. format === GPUTextureFormat.R32Sint ||
  43053. format === GPUTextureFormat.R32Float ||
  43054. format === GPUTextureFormat.RG16Uint ||
  43055. format === GPUTextureFormat.RG16Sint ||
  43056. format === GPUTextureFormat.RG16Float ||
  43057. format === GPUTextureFormat.RGBA8Unorm ||
  43058. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43059. format === GPUTextureFormat.RGBA8Snorm ||
  43060. format === GPUTextureFormat.RGBA8Uint ||
  43061. format === GPUTextureFormat.RGBA8Sint ||
  43062. format === GPUTextureFormat.BGRA8Unorm ||
  43063. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43064. // Packed 32-bit formats
  43065. format === GPUTextureFormat.RGB9E5UFloat ||
  43066. format === GPUTextureFormat.RGB10A2Unorm ||
  43067. format === GPUTextureFormat.RG11B10UFloat ||
  43068. format === GPUTextureFormat.Depth32Float ||
  43069. format === GPUTextureFormat.Depth24Plus ||
  43070. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43071. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43072. // 64-bit formats
  43073. if ( format === GPUTextureFormat.RG32Uint ||
  43074. format === GPUTextureFormat.RG32Sint ||
  43075. format === GPUTextureFormat.RG32Float ||
  43076. format === GPUTextureFormat.RGBA16Uint ||
  43077. format === GPUTextureFormat.RGBA16Sint ||
  43078. format === GPUTextureFormat.RGBA16Float ) return 8;
  43079. // 128-bit formats
  43080. if ( format === GPUTextureFormat.RGBA32Uint ||
  43081. format === GPUTextureFormat.RGBA32Sint ||
  43082. format === GPUTextureFormat.RGBA32Float ) return 16;
  43083. }
  43084. /**
  43085. * Returns the corresponding typed array type for the given GPU texture format.
  43086. *
  43087. * @private
  43088. * @param {String} format - The GPU texture format.
  43089. * @return {TypedArray.constructor} The typed array type.
  43090. */
  43091. _getTypedArrayType( format ) {
  43092. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43093. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43094. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43095. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43096. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43097. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43098. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43099. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43100. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43101. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43102. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43103. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43104. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43105. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43106. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43107. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43108. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43109. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43110. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43111. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43112. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43113. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43114. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43115. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43116. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43117. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43118. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43119. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43120. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43121. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43122. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43123. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43124. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43125. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43126. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43127. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43128. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43129. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43130. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43131. }
  43132. /**
  43133. * Returns the GPU dimensions for the given texture.
  43134. *
  43135. * @private
  43136. * @param {Texture} texture - The texture.
  43137. * @return {String} The GPU dimension.
  43138. */
  43139. _getDimension( texture ) {
  43140. let dimension;
  43141. if ( texture.isData3DTexture ) {
  43142. dimension = GPUTextureDimension.ThreeD;
  43143. } else {
  43144. dimension = GPUTextureDimension.TwoD;
  43145. }
  43146. return dimension;
  43147. }
  43148. }
  43149. /**
  43150. * Returns the GPU format for the given texture.
  43151. *
  43152. * @param {Texture} texture - The texture.
  43153. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  43154. * It is not necessary to apply the device for most formats.
  43155. * @return {String} The GPU format.
  43156. */
  43157. function getFormat( texture, device = null ) {
  43158. const format = texture.format;
  43159. const type = texture.type;
  43160. const colorSpace = texture.colorSpace;
  43161. let formatGPU;
  43162. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43163. switch ( format ) {
  43164. case RGBA_S3TC_DXT1_Format:
  43165. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43166. break;
  43167. case RGBA_S3TC_DXT3_Format:
  43168. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43169. break;
  43170. case RGBA_S3TC_DXT5_Format:
  43171. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43172. break;
  43173. case RGB_ETC2_Format:
  43174. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43175. break;
  43176. case RGBA_ETC2_EAC_Format:
  43177. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43178. break;
  43179. case RGBA_ASTC_4x4_Format:
  43180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43181. break;
  43182. case RGBA_ASTC_5x4_Format:
  43183. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43184. break;
  43185. case RGBA_ASTC_5x5_Format:
  43186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43187. break;
  43188. case RGBA_ASTC_6x5_Format:
  43189. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43190. break;
  43191. case RGBA_ASTC_6x6_Format:
  43192. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43193. break;
  43194. case RGBA_ASTC_8x5_Format:
  43195. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43196. break;
  43197. case RGBA_ASTC_8x6_Format:
  43198. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43199. break;
  43200. case RGBA_ASTC_8x8_Format:
  43201. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43202. break;
  43203. case RGBA_ASTC_10x5_Format:
  43204. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43205. break;
  43206. case RGBA_ASTC_10x6_Format:
  43207. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43208. break;
  43209. case RGBA_ASTC_10x8_Format:
  43210. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43211. break;
  43212. case RGBA_ASTC_10x10_Format:
  43213. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43214. break;
  43215. case RGBA_ASTC_12x10_Format:
  43216. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43217. break;
  43218. case RGBA_ASTC_12x12_Format:
  43219. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43220. break;
  43221. case RGBAFormat:
  43222. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43223. break;
  43224. default:
  43225. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43226. }
  43227. } else {
  43228. switch ( format ) {
  43229. case RGBAFormat:
  43230. switch ( type ) {
  43231. case ByteType:
  43232. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43233. break;
  43234. case ShortType:
  43235. formatGPU = GPUTextureFormat.RGBA16Sint;
  43236. break;
  43237. case UnsignedShortType:
  43238. formatGPU = GPUTextureFormat.RGBA16Uint;
  43239. break;
  43240. case UnsignedIntType:
  43241. formatGPU = GPUTextureFormat.RGBA32Uint;
  43242. break;
  43243. case IntType:
  43244. formatGPU = GPUTextureFormat.RGBA32Sint;
  43245. break;
  43246. case UnsignedByteType:
  43247. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43248. break;
  43249. case HalfFloatType:
  43250. formatGPU = GPUTextureFormat.RGBA16Float;
  43251. break;
  43252. case FloatType:
  43253. formatGPU = GPUTextureFormat.RGBA32Float;
  43254. break;
  43255. default:
  43256. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43257. }
  43258. break;
  43259. case RGBFormat:
  43260. switch ( type ) {
  43261. case UnsignedInt5999Type:
  43262. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43263. break;
  43264. default:
  43265. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43266. }
  43267. break;
  43268. case RedFormat:
  43269. switch ( type ) {
  43270. case ByteType:
  43271. formatGPU = GPUTextureFormat.R8Snorm;
  43272. break;
  43273. case ShortType:
  43274. formatGPU = GPUTextureFormat.R16Sint;
  43275. break;
  43276. case UnsignedShortType:
  43277. formatGPU = GPUTextureFormat.R16Uint;
  43278. break;
  43279. case UnsignedIntType:
  43280. formatGPU = GPUTextureFormat.R32Uint;
  43281. break;
  43282. case IntType:
  43283. formatGPU = GPUTextureFormat.R32Sint;
  43284. break;
  43285. case UnsignedByteType:
  43286. formatGPU = GPUTextureFormat.R8Unorm;
  43287. break;
  43288. case HalfFloatType:
  43289. formatGPU = GPUTextureFormat.R16Float;
  43290. break;
  43291. case FloatType:
  43292. formatGPU = GPUTextureFormat.R32Float;
  43293. break;
  43294. default:
  43295. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43296. }
  43297. break;
  43298. case RGFormat:
  43299. switch ( type ) {
  43300. case ByteType:
  43301. formatGPU = GPUTextureFormat.RG8Snorm;
  43302. break;
  43303. case ShortType:
  43304. formatGPU = GPUTextureFormat.RG16Sint;
  43305. break;
  43306. case UnsignedShortType:
  43307. formatGPU = GPUTextureFormat.RG16Uint;
  43308. break;
  43309. case UnsignedIntType:
  43310. formatGPU = GPUTextureFormat.RG32Uint;
  43311. break;
  43312. case IntType:
  43313. formatGPU = GPUTextureFormat.RG32Sint;
  43314. break;
  43315. case UnsignedByteType:
  43316. formatGPU = GPUTextureFormat.RG8Unorm;
  43317. break;
  43318. case HalfFloatType:
  43319. formatGPU = GPUTextureFormat.RG16Float;
  43320. break;
  43321. case FloatType:
  43322. formatGPU = GPUTextureFormat.RG32Float;
  43323. break;
  43324. default:
  43325. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43326. }
  43327. break;
  43328. case DepthFormat:
  43329. switch ( type ) {
  43330. case UnsignedShortType:
  43331. formatGPU = GPUTextureFormat.Depth16Unorm;
  43332. break;
  43333. case UnsignedIntType:
  43334. formatGPU = GPUTextureFormat.Depth24Plus;
  43335. break;
  43336. case FloatType:
  43337. formatGPU = GPUTextureFormat.Depth32Float;
  43338. break;
  43339. default:
  43340. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43341. }
  43342. break;
  43343. case DepthStencilFormat:
  43344. switch ( type ) {
  43345. case UnsignedInt248Type:
  43346. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43347. break;
  43348. case FloatType:
  43349. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43350. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43351. }
  43352. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43353. break;
  43354. default:
  43355. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43356. }
  43357. break;
  43358. case RedIntegerFormat:
  43359. switch ( type ) {
  43360. case IntType:
  43361. formatGPU = GPUTextureFormat.R32Sint;
  43362. break;
  43363. case UnsignedIntType:
  43364. formatGPU = GPUTextureFormat.R32Uint;
  43365. break;
  43366. default:
  43367. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43368. }
  43369. break;
  43370. case RGIntegerFormat:
  43371. switch ( type ) {
  43372. case IntType:
  43373. formatGPU = GPUTextureFormat.RG32Sint;
  43374. break;
  43375. case UnsignedIntType:
  43376. formatGPU = GPUTextureFormat.RG32Uint;
  43377. break;
  43378. default:
  43379. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43380. }
  43381. break;
  43382. case RGBAIntegerFormat:
  43383. switch ( type ) {
  43384. case IntType:
  43385. formatGPU = GPUTextureFormat.RGBA32Sint;
  43386. break;
  43387. case UnsignedIntType:
  43388. formatGPU = GPUTextureFormat.RGBA32Uint;
  43389. break;
  43390. default:
  43391. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43392. }
  43393. break;
  43394. default:
  43395. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43396. }
  43397. }
  43398. return formatGPU;
  43399. }
  43400. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43401. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43402. const wgslTypeLib$1 = {
  43403. 'f32': 'float',
  43404. 'i32': 'int',
  43405. 'u32': 'uint',
  43406. 'bool': 'bool',
  43407. 'vec2<f32>': 'vec2',
  43408. 'vec2<i32>': 'ivec2',
  43409. 'vec2<u32>': 'uvec2',
  43410. 'vec2<bool>': 'bvec2',
  43411. 'vec2f': 'vec2',
  43412. 'vec2i': 'ivec2',
  43413. 'vec2u': 'uvec2',
  43414. 'vec2b': 'bvec2',
  43415. 'vec3<f32>': 'vec3',
  43416. 'vec3<i32>': 'ivec3',
  43417. 'vec3<u32>': 'uvec3',
  43418. 'vec3<bool>': 'bvec3',
  43419. 'vec3f': 'vec3',
  43420. 'vec3i': 'ivec3',
  43421. 'vec3u': 'uvec3',
  43422. 'vec3b': 'bvec3',
  43423. 'vec4<f32>': 'vec4',
  43424. 'vec4<i32>': 'ivec4',
  43425. 'vec4<u32>': 'uvec4',
  43426. 'vec4<bool>': 'bvec4',
  43427. 'vec4f': 'vec4',
  43428. 'vec4i': 'ivec4',
  43429. 'vec4u': 'uvec4',
  43430. 'vec4b': 'bvec4',
  43431. 'mat2x2<f32>': 'mat2',
  43432. 'mat2x2f': 'mat2',
  43433. 'mat3x3<f32>': 'mat3',
  43434. 'mat3x3f': 'mat3',
  43435. 'mat4x4<f32>': 'mat4',
  43436. 'mat4x4f': 'mat4',
  43437. 'sampler': 'sampler',
  43438. 'texture_1d': 'texture',
  43439. 'texture_2d': 'texture',
  43440. 'texture_2d_array': 'texture',
  43441. 'texture_multisampled_2d': 'cubeTexture',
  43442. 'texture_depth_2d': 'depthTexture',
  43443. 'texture_depth_multisampled_2d': 'depthTexture',
  43444. 'texture_3d': 'texture3D',
  43445. 'texture_cube': 'cubeTexture',
  43446. 'texture_cube_array': 'cubeTexture',
  43447. 'texture_storage_1d': 'storageTexture',
  43448. 'texture_storage_2d': 'storageTexture',
  43449. 'texture_storage_2d_array': 'storageTexture',
  43450. 'texture_storage_3d': 'storageTexture'
  43451. };
  43452. const parse = ( source ) => {
  43453. source = source.trim();
  43454. const declaration = source.match( declarationRegexp );
  43455. if ( declaration !== null && declaration.length === 4 ) {
  43456. const inputsCode = declaration[ 2 ];
  43457. const propsMatches = [];
  43458. let match = null;
  43459. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43460. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43461. }
  43462. // Process matches to correctly pair names and types
  43463. const inputs = [];
  43464. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43465. const { name, type } = propsMatches[ i ];
  43466. let resolvedType = type;
  43467. if ( resolvedType.startsWith( 'ptr' ) ) {
  43468. resolvedType = 'pointer';
  43469. } else {
  43470. if ( resolvedType.startsWith( 'texture' ) ) {
  43471. resolvedType = type.split( '<' )[ 0 ];
  43472. }
  43473. resolvedType = wgslTypeLib$1[ resolvedType ];
  43474. }
  43475. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43476. }
  43477. const blockCode = source.substring( declaration[ 0 ].length );
  43478. const outputType = declaration[ 3 ] || 'void';
  43479. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43480. const type = wgslTypeLib$1[ outputType ] || outputType;
  43481. return {
  43482. type,
  43483. inputs,
  43484. name,
  43485. inputsCode,
  43486. blockCode,
  43487. outputType
  43488. };
  43489. } else {
  43490. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43491. }
  43492. };
  43493. /**
  43494. * This class represents a WSL node function.
  43495. *
  43496. * @augments NodeFunction
  43497. */
  43498. class WGSLNodeFunction extends NodeFunction {
  43499. /**
  43500. * Constructs a new WGSL node function.
  43501. *
  43502. * @param {String} source - The WGSL source.
  43503. */
  43504. constructor( source ) {
  43505. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43506. super( type, inputs, name );
  43507. this.inputsCode = inputsCode;
  43508. this.blockCode = blockCode;
  43509. this.outputType = outputType;
  43510. }
  43511. /**
  43512. * This method returns the WGSL code of the node function.
  43513. *
  43514. * @param {String} [name=this.name] - The function's name.
  43515. * @return {String} The shader code.
  43516. */
  43517. getCode( name = this.name ) {
  43518. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43519. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43520. }
  43521. }
  43522. /**
  43523. * A WGSL node parser.
  43524. *
  43525. * @augments NodeParser
  43526. */
  43527. class WGSLNodeParser extends NodeParser {
  43528. /**
  43529. * The method parses the given WGSL code an returns a node function.
  43530. *
  43531. * @param {String} source - The WGSL code.
  43532. * @return {WGSLNodeFunction} A node function.
  43533. */
  43534. parseFunction( source ) {
  43535. return new WGSLNodeFunction( source );
  43536. }
  43537. }
  43538. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43539. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  43540. const accessNames = {
  43541. [ NodeAccess.READ_ONLY ]: 'read',
  43542. [ NodeAccess.WRITE_ONLY ]: 'write',
  43543. [ NodeAccess.READ_WRITE ]: 'read_write'
  43544. };
  43545. const wrapNames = {
  43546. [ RepeatWrapping ]: 'repeat',
  43547. [ ClampToEdgeWrapping ]: 'clamp',
  43548. [ MirroredRepeatWrapping ]: 'mirror'
  43549. };
  43550. const gpuShaderStageLib = {
  43551. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43552. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43553. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43554. };
  43555. const supports = {
  43556. instance: true,
  43557. swizzleAssign: false,
  43558. storageBuffer: true
  43559. };
  43560. const wgslFnOpLib = {
  43561. '^^': 'tsl_xor'
  43562. };
  43563. const wgslTypeLib = {
  43564. float: 'f32',
  43565. int: 'i32',
  43566. uint: 'u32',
  43567. bool: 'bool',
  43568. color: 'vec3<f32>',
  43569. vec2: 'vec2<f32>',
  43570. ivec2: 'vec2<i32>',
  43571. uvec2: 'vec2<u32>',
  43572. bvec2: 'vec2<bool>',
  43573. vec3: 'vec3<f32>',
  43574. ivec3: 'vec3<i32>',
  43575. uvec3: 'vec3<u32>',
  43576. bvec3: 'vec3<bool>',
  43577. vec4: 'vec4<f32>',
  43578. ivec4: 'vec4<i32>',
  43579. uvec4: 'vec4<u32>',
  43580. bvec4: 'vec4<bool>',
  43581. mat2: 'mat2x2<f32>',
  43582. mat3: 'mat3x3<f32>',
  43583. mat4: 'mat4x4<f32>'
  43584. };
  43585. const wgslCodeCache = {};
  43586. const wgslPolyfill = {
  43587. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43588. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43589. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43590. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43591. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43592. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43593. 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 ); }' ),
  43594. 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 ); }' ),
  43595. 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 ); }' ),
  43596. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  43597. 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 ); }' ),
  43598. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  43599. biquadraticTexture: new CodeNode( /* wgsl */`
  43600. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  43601. let res = vec2f( iRes );
  43602. let uvScaled = coord * res;
  43603. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43604. // https://www.shadertoy.com/view/WtyXRy
  43605. let uv = uvWrapping - 0.5;
  43606. let iuv = floor( uv );
  43607. let f = fract( uv );
  43608. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  43609. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  43610. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  43611. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  43612. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43613. }
  43614. ` )
  43615. };
  43616. const wgslMethods = {
  43617. dFdx: 'dpdx',
  43618. dFdy: '- dpdy',
  43619. mod_float: 'tsl_mod_float',
  43620. mod_vec2: 'tsl_mod_vec2',
  43621. mod_vec3: 'tsl_mod_vec3',
  43622. mod_vec4: 'tsl_mod_vec4',
  43623. equals_bool: 'tsl_equals_bool',
  43624. equals_bvec2: 'tsl_equals_bvec2',
  43625. equals_bvec3: 'tsl_equals_bvec3',
  43626. equals_bvec4: 'tsl_equals_bvec4',
  43627. inversesqrt: 'inverseSqrt',
  43628. bitcast: 'bitcast<f32>'
  43629. };
  43630. // WebGPU issue: does not support pow() with negative base on Windows
  43631. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  43632. 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 ); }' );
  43633. 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 ] );
  43634. 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 ] );
  43635. 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 ] );
  43636. wgslMethods.pow_float = 'tsl_pow_float';
  43637. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43638. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43639. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43640. }
  43641. //
  43642. let diagnostics = '';
  43643. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  43644. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43645. }
  43646. /**
  43647. * A node builder targeting WGSL.
  43648. *
  43649. * This module generates WGSL shader code from node materials and also
  43650. * generates the respective bindings and vertex buffer definitions. These
  43651. * data are later used by the renderer to create render and compute pipelines
  43652. * for render objects.
  43653. *
  43654. * @augments NodeBuilder
  43655. */
  43656. class WGSLNodeBuilder extends NodeBuilder {
  43657. /**
  43658. * Constructs a new WGSL node builder renderer.
  43659. *
  43660. * @param {Object3D} object - The 3D object.
  43661. * @param {Renderer} renderer - The renderer.
  43662. */
  43663. constructor( object, renderer ) {
  43664. super( object, renderer, new WGSLNodeParser() );
  43665. /**
  43666. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  43667. * another dictionary which manages UBOs per group ('render','frame','object').
  43668. *
  43669. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  43670. */
  43671. this.uniformGroups = {};
  43672. /**
  43673. * A dictionary that holds for each shader stage a Map of builtins.
  43674. *
  43675. * @type {Object<String,Map<String,Object>>}
  43676. */
  43677. this.builtins = {};
  43678. /**
  43679. * A dictionary that holds for each shader stage a Set of directives.
  43680. *
  43681. * @type {Object<String,Set<String>>}
  43682. */
  43683. this.directives = {};
  43684. /**
  43685. * A map for managing scope arrays. Only relevant for when using
  43686. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  43687. *
  43688. * @type {Map<String,Object>}
  43689. */
  43690. this.scopedArrays = new Map();
  43691. }
  43692. /**
  43693. * Checks if the given texture requires a manual conversion to the working color space.
  43694. *
  43695. * @param {Texture} texture - The texture to check.
  43696. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  43697. */
  43698. needsToWorkingColorSpace( texture ) {
  43699. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43700. }
  43701. /**
  43702. * Generates the WGSL snippet for sampled textures.
  43703. *
  43704. * @private
  43705. * @param {Texture} texture - The texture.
  43706. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43707. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43708. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43709. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43710. * @return {String} The WGSL snippet.
  43711. */
  43712. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43713. if ( shaderStage === 'fragment' ) {
  43714. if ( depthSnippet ) {
  43715. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43716. } else {
  43717. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43718. }
  43719. } else if ( this.isFilteredTexture( texture ) ) {
  43720. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43721. } else {
  43722. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  43723. }
  43724. }
  43725. /**
  43726. * Generates the WGSL snippet when sampling video textures.
  43727. *
  43728. * @private
  43729. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43730. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43731. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43732. * @return {String} The WGSL snippet.
  43733. */
  43734. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43735. if ( shaderStage === 'fragment' ) {
  43736. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43737. } else {
  43738. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43739. }
  43740. }
  43741. /**
  43742. * Generates the WGSL snippet when sampling textures with explicit mip level.
  43743. *
  43744. * @private
  43745. * @param {Texture} texture - The texture.
  43746. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43747. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43748. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43749. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43750. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43751. * @return {String} The WGSL snippet.
  43752. */
  43753. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43754. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  43755. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43756. } else if ( this.isFilteredTexture( texture ) ) {
  43757. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43758. } else {
  43759. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  43760. }
  43761. }
  43762. /**
  43763. * Generates a wrap function used in context of textures.
  43764. *
  43765. * @param {Texture} texture - The texture to generate the function for.
  43766. * @return {String} The name of the generated function.
  43767. */
  43768. generateWrapFunction( texture ) {
  43769. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  43770. let nodeCode = wgslCodeCache[ functionName ];
  43771. if ( nodeCode === undefined ) {
  43772. const includes = [];
  43773. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  43774. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  43775. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  43776. const addWrapSnippet = ( wrap, axis ) => {
  43777. if ( wrap === RepeatWrapping ) {
  43778. includes.push( wgslPolyfill.repeatWrapping_float );
  43779. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  43780. } else if ( wrap === ClampToEdgeWrapping ) {
  43781. includes.push( wgslPolyfill.clampWrapping_float );
  43782. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  43783. } else if ( wrap === MirroredRepeatWrapping ) {
  43784. includes.push( wgslPolyfill.mirrorWrapping_float );
  43785. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  43786. } else {
  43787. code += `\t\tcoord.${ axis }`;
  43788. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  43789. }
  43790. };
  43791. addWrapSnippet( texture.wrapS, 'x' );
  43792. code += ',\n';
  43793. addWrapSnippet( texture.wrapT, 'y' );
  43794. if ( texture.isData3DTexture ) {
  43795. code += ',\n';
  43796. addWrapSnippet( texture.wrapR, 'z' );
  43797. }
  43798. code += '\n\t);\n\n}\n';
  43799. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  43800. }
  43801. nodeCode.build( this );
  43802. return functionName;
  43803. }
  43804. /**
  43805. * Generates a WGSL variable that holds the texture dimension of the given texture.
  43806. * It also returns information about the the number of layers (elements) of an arrayed
  43807. * texture as well as the cube face count of cube textures.
  43808. *
  43809. * @param {Texture} texture - The texture to generate the function for.
  43810. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43811. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43812. * @return {String} The name of the dimension variable.
  43813. */
  43814. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  43815. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  43816. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  43817. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  43818. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  43819. let textureDimensionsParams;
  43820. let dimensionType;
  43821. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  43822. const isMultisampled = primarySamples > 1;
  43823. if ( texture.isData3DTexture ) {
  43824. dimensionType = 'vec3<u32>';
  43825. } else {
  43826. // Regular 2D textures, depth textures, etc.
  43827. dimensionType = 'vec2<u32>';
  43828. }
  43829. // Build parameters string based on texture type and multisampling
  43830. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  43831. textureDimensionsParams = textureProperty;
  43832. } else {
  43833. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  43834. }
  43835. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  43836. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  43837. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43838. textureData.arrayLayerCount = new VarNode(
  43839. new ExpressionNode(
  43840. `textureNumLayers(${textureProperty})`,
  43841. 'u32'
  43842. )
  43843. );
  43844. }
  43845. // For cube textures, we know it's always 6 faces
  43846. if ( texture.isTextureCube ) {
  43847. textureData.cubeFaceCount = new VarNode(
  43848. new ExpressionNode( '6u', 'u32' )
  43849. );
  43850. }
  43851. }
  43852. return textureDimensionNode.build( this );
  43853. }
  43854. /**
  43855. * Generates the WGSL snippet for a manual filtered texture.
  43856. *
  43857. * @param {Texture} texture - The texture.
  43858. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43859. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43860. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43861. * @return {String} The WGSL snippet.
  43862. */
  43863. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  43864. this._include( 'biquadraticTexture' );
  43865. const wrapFunction = this.generateWrapFunction( texture );
  43866. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43867. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  43868. }
  43869. /**
  43870. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  43871. * Since it's a lookup, no sampling or filtering is applied.
  43872. *
  43873. * @param {Texture} texture - The texture.
  43874. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43875. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43876. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43877. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43878. * @return {String} The WGSL snippet.
  43879. */
  43880. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  43881. const wrapFunction = this.generateWrapFunction( texture );
  43882. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43883. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  43884. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  43885. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  43886. }
  43887. /**
  43888. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  43889. *
  43890. * @param {Texture} texture - The texture.
  43891. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43892. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43893. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43894. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43895. * @return {String} The WGSL snippet.
  43896. */
  43897. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43898. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  43899. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  43900. } else if ( depthSnippet ) {
  43901. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  43902. } else {
  43903. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  43904. }
  43905. }
  43906. /**
  43907. * Generates the WGSL snippet that writes a single texel to a texture.
  43908. *
  43909. * @param {Texture} texture - The texture.
  43910. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43911. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43912. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  43913. * @return {String} The WGSL snippet.
  43914. */
  43915. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43916. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43917. }
  43918. /**
  43919. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  43920. *
  43921. * @param {Texture} texture - The texture.
  43922. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  43923. */
  43924. isSampleCompare( texture ) {
  43925. return texture.isDepthTexture === true && texture.compareFunction !== null;
  43926. }
  43927. /**
  43928. * Returns `true` if the given texture is unfilterable.
  43929. *
  43930. * @param {Texture} texture - The texture.
  43931. * @return {Boolean} Whether the given texture is unfilterable or not.
  43932. */
  43933. isUnfilterable( texture ) {
  43934. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  43935. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  43936. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  43937. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  43938. }
  43939. /**
  43940. * Generates the WGSL snippet for sampling/loading the given texture.
  43941. *
  43942. * @param {Texture} texture - The texture.
  43943. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43944. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43945. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43946. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43947. * @return {String} The WGSL snippet.
  43948. */
  43949. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43950. let snippet = null;
  43951. if ( texture.isVideoTexture === true ) {
  43952. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43953. } else if ( this.isUnfilterable( texture ) ) {
  43954. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  43955. } else {
  43956. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43957. }
  43958. return snippet;
  43959. }
  43960. /**
  43961. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  43962. *
  43963. * @param {Texture} texture - The texture.
  43964. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43965. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43966. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  43967. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43968. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43969. * @return {String} The WGSL snippet.
  43970. */
  43971. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43972. if ( shaderStage === 'fragment' ) {
  43973. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43974. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43975. } else {
  43976. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43977. }
  43978. }
  43979. /**
  43980. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  43981. * against a reference value.
  43982. *
  43983. * @param {Texture} texture - The texture.
  43984. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43985. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43986. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  43987. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43988. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43989. * @return {String} The WGSL snippet.
  43990. */
  43991. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43992. if ( shaderStage === 'fragment' ) {
  43993. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43994. } else {
  43995. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43996. }
  43997. }
  43998. /**
  43999. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44000. *
  44001. * @param {Texture} texture - The texture.
  44002. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44003. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44004. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44005. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44006. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44007. * @return {String} The WGSL snippet.
  44008. */
  44009. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44010. let snippet = null;
  44011. if ( texture.isVideoTexture === true ) {
  44012. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44013. } else {
  44014. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  44015. }
  44016. return snippet;
  44017. }
  44018. /**
  44019. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  44020. *
  44021. * @param {Texture} texture - The texture.
  44022. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44023. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44024. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  44025. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44026. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44027. * @return {String} The WGSL snippet.
  44028. */
  44029. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44030. if ( shaderStage === 'fragment' ) {
  44031. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  44032. } else {
  44033. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  44034. }
  44035. }
  44036. /**
  44037. * Returns a WGSL snippet that represents the property name of the given node.
  44038. *
  44039. * @param {Node} node - The node.
  44040. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44041. * @return {String} The property name.
  44042. */
  44043. getPropertyName( node, shaderStage = this.shaderStage ) {
  44044. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  44045. if ( shaderStage === 'vertex' ) {
  44046. return `varyings.${ node.name }`;
  44047. }
  44048. } else if ( node.isNodeUniform === true ) {
  44049. const name = node.name;
  44050. const type = node.type;
  44051. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44052. return name;
  44053. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44054. return `NodeBuffer_${ node.id }.${name}`;
  44055. } else {
  44056. return node.groupNode.name + '.' + name;
  44057. }
  44058. }
  44059. return super.getPropertyName( node );
  44060. }
  44061. /**
  44062. * Returns the output struct name.
  44063. *
  44064. * @return {String} The name of the output struct.
  44065. */
  44066. getOutputStructName() {
  44067. return 'output';
  44068. }
  44069. /**
  44070. * Returns uniforms group count for the given shader stage.
  44071. *
  44072. * @private
  44073. * @param {String} shaderStage - The shader stage.
  44074. * @return {Number} The uniforms group count for the given shader stage.
  44075. */
  44076. _getUniformGroupCount( shaderStage ) {
  44077. return Object.keys( this.uniforms[ shaderStage ] ).length;
  44078. }
  44079. /**
  44080. * Returns the native shader operator name for a given generic name.
  44081. *
  44082. * @param {String} op - The operator name to resolve.
  44083. * @return {String} The resolved operator name.
  44084. */
  44085. getFunctionOperator( op ) {
  44086. const fnOp = wgslFnOpLib[ op ];
  44087. if ( fnOp !== undefined ) {
  44088. this._include( fnOp );
  44089. return fnOp;
  44090. }
  44091. return null;
  44092. }
  44093. /**
  44094. * Returns the node access for the given node and shader stage.
  44095. *
  44096. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44097. * @param {String} shaderStage - The shader stage.
  44098. * @return {String} The node access.
  44099. */
  44100. getNodeAccess( node, shaderStage ) {
  44101. if ( shaderStage !== 'compute' )
  44102. return NodeAccess.READ_ONLY;
  44103. return node.access;
  44104. }
  44105. /**
  44106. * Returns A WGSL snippet representing the storage access.
  44107. *
  44108. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44109. * @param {String} shaderStage - The shader stage.
  44110. * @return {String} The WGSL snippet representing the storage access.
  44111. */
  44112. getStorageAccess( node, shaderStage ) {
  44113. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  44114. }
  44115. /**
  44116. * This method is one of the more important ones since it's responsible
  44117. * for generating a matching binding instance for the given uniform node.
  44118. *
  44119. * These bindings are later used in the renderer to create bind groups
  44120. * and layouts.
  44121. *
  44122. * @param {UniformNode} node - The uniform node.
  44123. * @param {String} type - The node data type.
  44124. * @param {String} shaderStage - The shader stage.
  44125. * @param {String?} [name=null] - An optional uniform name.
  44126. * @return {NodeUniform} The node uniform object.
  44127. */
  44128. getUniformFromNode( node, type, shaderStage, name = null ) {
  44129. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44130. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44131. if ( nodeData.uniformGPU === undefined ) {
  44132. let uniformGPU;
  44133. const group = node.groupNode;
  44134. const groupName = group.name;
  44135. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44136. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44137. let texture = null;
  44138. const access = this.getNodeAccess( node, shaderStage );
  44139. if ( type === 'texture' || type === 'storageTexture' ) {
  44140. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  44141. } else if ( type === 'cubeTexture' ) {
  44142. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  44143. } else if ( type === 'texture3D' ) {
  44144. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  44145. }
  44146. texture.store = node.isStorageTextureNode === true;
  44147. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44148. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44149. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44150. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44151. bindings.push( sampler, texture );
  44152. uniformGPU = [ sampler, texture ];
  44153. } else {
  44154. bindings.push( texture );
  44155. uniformGPU = [ texture ];
  44156. }
  44157. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44158. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  44159. const buffer = new bufferClass( node, group );
  44160. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44161. bindings.push( buffer );
  44162. uniformGPU = buffer;
  44163. } else {
  44164. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44165. let uniformsGroup = uniformsStage[ groupName ];
  44166. if ( uniformsGroup === undefined ) {
  44167. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44168. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44169. uniformsStage[ groupName ] = uniformsGroup;
  44170. bindings.push( uniformsGroup );
  44171. }
  44172. uniformGPU = this.getNodeUniform( uniformNode, type );
  44173. uniformsGroup.addUniform( uniformGPU );
  44174. }
  44175. nodeData.uniformGPU = uniformGPU;
  44176. }
  44177. return uniformNode;
  44178. }
  44179. /**
  44180. * This method should be used whenever builtins are required in nodes.
  44181. * The internal builtins data structure will make sure builtins are
  44182. * defined in the WGSL source.
  44183. *
  44184. * @param {String} name - The builtin name.
  44185. * @param {String} property - The property name.
  44186. * @param {String} type - The node data type.
  44187. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44188. * @return {String} The property name.
  44189. */
  44190. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44191. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44192. if ( map.has( name ) === false ) {
  44193. map.set( name, {
  44194. name,
  44195. property,
  44196. type
  44197. } );
  44198. }
  44199. return property;
  44200. }
  44201. /**
  44202. * Returns `true` if the given builtin is defined in the given shader stage.
  44203. *
  44204. * @param {String} name - The builtin name.
  44205. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44206. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  44207. */
  44208. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44209. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44210. }
  44211. /**
  44212. * Returns the vertex index builtin.
  44213. *
  44214. * @return {String} The vertex index.
  44215. */
  44216. getVertexIndex() {
  44217. if ( this.shaderStage === 'vertex' ) {
  44218. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44219. }
  44220. return 'vertexIndex';
  44221. }
  44222. /**
  44223. * Builds the given shader node.
  44224. *
  44225. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44226. * @return {String} The WGSL function code.
  44227. */
  44228. buildFunctionCode( shaderNode ) {
  44229. const layout = shaderNode.layout;
  44230. const flowData = this.flowShaderNode( shaderNode );
  44231. const parameters = [];
  44232. for ( const input of layout.inputs ) {
  44233. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44234. }
  44235. //
  44236. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44237. ${ flowData.vars }
  44238. ${ flowData.code }
  44239. `;
  44240. if ( flowData.result ) {
  44241. code += `\treturn ${ flowData.result };\n`;
  44242. }
  44243. code += '\n}\n';
  44244. //
  44245. return code;
  44246. }
  44247. /**
  44248. * Returns the instance index builtin.
  44249. *
  44250. * @return {String} The instance index.
  44251. */
  44252. getInstanceIndex() {
  44253. if ( this.shaderStage === 'vertex' ) {
  44254. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44255. }
  44256. return 'instanceIndex';
  44257. }
  44258. /**
  44259. * Returns the invocation local index builtin.
  44260. *
  44261. * @return {String} The invocation local index.
  44262. */
  44263. getInvocationLocalIndex() {
  44264. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44265. }
  44266. /**
  44267. * Returns the subgroup size builtin.
  44268. *
  44269. * @return {String} The subgroup size.
  44270. */
  44271. getSubgroupSize() {
  44272. this.enableSubGroups();
  44273. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44274. }
  44275. /**
  44276. * Returns the invocation subgroup index builtin.
  44277. *
  44278. * @return {String} The invocation subgroup index.
  44279. */
  44280. getInvocationSubgroupIndex() {
  44281. this.enableSubGroups();
  44282. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44283. }
  44284. /**
  44285. * Returns the subgroup index builtin.
  44286. *
  44287. * @return {String} The subgroup index.
  44288. */
  44289. getSubgroupIndex() {
  44290. this.enableSubGroups();
  44291. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44292. }
  44293. /**
  44294. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  44295. *
  44296. * @return {null} Null.
  44297. */
  44298. getDrawIndex() {
  44299. return null;
  44300. }
  44301. /**
  44302. * Returns the front facing builtin.
  44303. *
  44304. * @return {String} The front facing builtin.
  44305. */
  44306. getFrontFacing() {
  44307. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44308. }
  44309. /**
  44310. * Returns the frag coord builtin.
  44311. *
  44312. * @return {String} The frag coord builtin.
  44313. */
  44314. getFragCoord() {
  44315. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44316. }
  44317. /**
  44318. * Returns the frag depth builtin.
  44319. *
  44320. * @return {String} The frag depth builtin.
  44321. */
  44322. getFragDepth() {
  44323. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44324. }
  44325. /**
  44326. * Returns the clip distances builtin.
  44327. *
  44328. * @return {String} The clip distances builtin.
  44329. */
  44330. getClipDistance() {
  44331. return 'varyings.hw_clip_distances';
  44332. }
  44333. /**
  44334. * Whether to flip texture data along its vertical axis or not.
  44335. *
  44336. * @return {Boolean} Returns always `false` in context of WGSL.
  44337. */
  44338. isFlipY() {
  44339. return false;
  44340. }
  44341. /**
  44342. * Enables the given directive for the given shader stage.
  44343. *
  44344. * @param {String} name - The directive name.
  44345. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  44346. */
  44347. enableDirective( name, shaderStage = this.shaderStage ) {
  44348. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44349. stage.add( name );
  44350. }
  44351. /**
  44352. * Returns the directives of the given shader stage as a WGSL string.
  44353. *
  44354. * @param {String} shaderStage - The shader stage.
  44355. * @return {String} A WGSL snippet that enables the directives of the given stage.
  44356. */
  44357. getDirectives( shaderStage ) {
  44358. const snippets = [];
  44359. const directives = this.directives[ shaderStage ];
  44360. if ( directives !== undefined ) {
  44361. for ( const directive of directives ) {
  44362. snippets.push( `enable ${directive};` );
  44363. }
  44364. }
  44365. return snippets.join( '\n' );
  44366. }
  44367. /**
  44368. * Enables the 'subgroups' directive.
  44369. */
  44370. enableSubGroups() {
  44371. this.enableDirective( 'subgroups' );
  44372. }
  44373. /**
  44374. * Enables the 'subgroups-f16' directive.
  44375. */
  44376. enableSubgroupsF16() {
  44377. this.enableDirective( 'subgroups-f16' );
  44378. }
  44379. /**
  44380. * Enables the 'clip_distances' directive.
  44381. */
  44382. enableClipDistances() {
  44383. this.enableDirective( 'clip_distances' );
  44384. }
  44385. /**
  44386. * Enables the 'f16' directive.
  44387. */
  44388. enableShaderF16() {
  44389. this.enableDirective( 'f16' );
  44390. }
  44391. /**
  44392. * Enables the 'dual_source_blending' directive.
  44393. */
  44394. enableDualSourceBlending() {
  44395. this.enableDirective( 'dual_source_blending' );
  44396. }
  44397. /**
  44398. * Enables hardware clipping.
  44399. *
  44400. * @param {String} planeCount - The clipping plane count.
  44401. */
  44402. enableHardwareClipping( planeCount ) {
  44403. this.enableClipDistances();
  44404. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  44405. }
  44406. /**
  44407. * Returns the builtins of the given shader stage as a WGSL string.
  44408. *
  44409. * @param {String} shaderStage - The shader stage.
  44410. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  44411. */
  44412. getBuiltins( shaderStage ) {
  44413. const snippets = [];
  44414. const builtins = this.builtins[ shaderStage ];
  44415. if ( builtins !== undefined ) {
  44416. for ( const { name, property, type } of builtins.values() ) {
  44417. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44418. }
  44419. }
  44420. return snippets.join( ',\n\t' );
  44421. }
  44422. /**
  44423. * This method should be used when a new scoped buffer is used in context of
  44424. * compute shaders. It adds the array to the internal data structure which is
  44425. * later used to generate the respective WGSL.
  44426. *
  44427. * @param {String} name - The array name.
  44428. * @param {String} scope - The scope.
  44429. * @param {String} bufferType - The buffer type.
  44430. * @param {String} bufferCount - The buffer count.
  44431. * @return {String} The array name.
  44432. */
  44433. getScopedArray( name, scope, bufferType, bufferCount ) {
  44434. if ( this.scopedArrays.has( name ) === false ) {
  44435. this.scopedArrays.set( name, {
  44436. name,
  44437. scope,
  44438. bufferType,
  44439. bufferCount
  44440. } );
  44441. }
  44442. return name;
  44443. }
  44444. /**
  44445. * Returns the scoped arrays of the given shader stage as a WGSL string.
  44446. *
  44447. * @param {String} shaderStage - The shader stage.
  44448. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  44449. * Returns `undefined` when used in the vertex or fragment stage.
  44450. */
  44451. getScopedArrays( shaderStage ) {
  44452. if ( shaderStage !== 'compute' ) {
  44453. return;
  44454. }
  44455. const snippets = [];
  44456. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  44457. const type = this.getType( bufferType );
  44458. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  44459. }
  44460. return snippets.join( '\n' );
  44461. }
  44462. /**
  44463. * Returns the shader attributes of the given shader stage as a WGSL string.
  44464. *
  44465. * @param {String} shaderStage - The shader stage.
  44466. * @return {String} The WGSL snippet that defines the shader attributes.
  44467. */
  44468. getAttributes( shaderStage ) {
  44469. const snippets = [];
  44470. if ( shaderStage === 'compute' ) {
  44471. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  44472. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  44473. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  44474. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  44475. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  44476. this.enableDirective( 'subgroups', shaderStage );
  44477. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44478. }
  44479. }
  44480. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44481. const builtins = this.getBuiltins( 'attribute' );
  44482. if ( builtins ) snippets.push( builtins );
  44483. const attributes = this.getAttributesArray();
  44484. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  44485. const attribute = attributes[ index ];
  44486. const name = attribute.name;
  44487. const type = this.getType( attribute.type );
  44488. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  44489. }
  44490. }
  44491. return snippets.join( ',\n\t' );
  44492. }
  44493. /**
  44494. * Returns the members of the given struct type node as a WGSL string.
  44495. *
  44496. * @param {StructTypeNode} struct - The struct type node.
  44497. * @return {String} The WGSL snippet that defines the struct members.
  44498. */
  44499. getStructMembers( struct ) {
  44500. const snippets = [];
  44501. const members = struct.getMemberTypes();
  44502. for ( let i = 0; i < members.length; i ++ ) {
  44503. const member = members[ i ];
  44504. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  44505. }
  44506. const builtins = this.getBuiltins( 'output' );
  44507. if ( builtins ) snippets.push( '\t' + builtins );
  44508. return snippets.join( ',\n' );
  44509. }
  44510. /**
  44511. * Returns the structs of the given shader stage as a WGSL string.
  44512. *
  44513. * @param {String} shaderStage - The shader stage.
  44514. * @return {String} The WGSL snippet that defines the structs.
  44515. */
  44516. getStructs( shaderStage ) {
  44517. const snippets = [];
  44518. const structs = this.structs[ shaderStage ];
  44519. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  44520. const struct = structs[ index ];
  44521. const name = struct.name;
  44522. let snippet = `\struct ${ name } {\n`;
  44523. snippet += this.getStructMembers( struct );
  44524. snippet += '\n}';
  44525. snippets.push( snippet );
  44526. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  44527. }
  44528. return snippets.join( '\n\n' );
  44529. }
  44530. /**
  44531. * Returns a WGSL string representing a variable.
  44532. *
  44533. * @param {String} type - The variable's type.
  44534. * @param {String} name - The variable's name.
  44535. * @return {String} The WGSL snippet that defines a variable.
  44536. */
  44537. getVar( type, name ) {
  44538. return `var ${ name } : ${ this.getType( type ) }`;
  44539. }
  44540. /**
  44541. * Returns the variables of the given shader stage as a WGSL string.
  44542. *
  44543. * @param {String} shaderStage - The shader stage.
  44544. * @return {String} The WGSL snippet that defines the variables.
  44545. */
  44546. getVars( shaderStage ) {
  44547. const snippets = [];
  44548. const vars = this.vars[ shaderStage ];
  44549. if ( vars !== undefined ) {
  44550. for ( const variable of vars ) {
  44551. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  44552. }
  44553. }
  44554. return `\n${ snippets.join( '\n' ) }\n`;
  44555. }
  44556. /**
  44557. * Returns the varyings of the given shader stage as a WGSL string.
  44558. *
  44559. * @param {String} shaderStage - The shader stage.
  44560. * @return {String} The WGSL snippet that defines the varyings.
  44561. */
  44562. getVaryings( shaderStage ) {
  44563. const snippets = [];
  44564. if ( shaderStage === 'vertex' ) {
  44565. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  44566. }
  44567. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  44568. const varyings = this.varyings;
  44569. const vars = this.vars[ shaderStage ];
  44570. for ( let index = 0; index < varyings.length; index ++ ) {
  44571. const varying = varyings[ index ];
  44572. if ( varying.needsInterpolation ) {
  44573. let attributesSnippet = `@location( ${index} )`;
  44574. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  44575. attributesSnippet += ' @interpolate( flat )';
  44576. }
  44577. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  44578. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  44579. vars.push( varying );
  44580. }
  44581. }
  44582. }
  44583. const builtins = this.getBuiltins( shaderStage );
  44584. if ( builtins ) snippets.push( builtins );
  44585. const code = snippets.join( ',\n\t' );
  44586. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  44587. }
  44588. /**
  44589. * Returns the uniforms of the given shader stage as a WGSL string.
  44590. *
  44591. * @param {String} shaderStage - The shader stage.
  44592. * @return {String} The WGSL snippet that defines the uniforms.
  44593. */
  44594. getUniforms( shaderStage ) {
  44595. const uniforms = this.uniforms[ shaderStage ];
  44596. const bindingSnippets = [];
  44597. const bufferSnippets = [];
  44598. const structSnippets = [];
  44599. const uniformGroups = {};
  44600. for ( const uniform of uniforms ) {
  44601. const groupName = uniform.groupNode.name;
  44602. const uniformIndexes = this.bindingsIndexes[ groupName ];
  44603. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  44604. const texture = uniform.node.value;
  44605. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  44606. if ( this.isSampleCompare( texture ) ) {
  44607. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  44608. } else {
  44609. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  44610. }
  44611. }
  44612. let textureType;
  44613. let multisampled = '';
  44614. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44615. if ( primarySamples > 1 ) {
  44616. multisampled = '_multisampled';
  44617. }
  44618. if ( texture.isCubeTexture === true ) {
  44619. textureType = 'texture_cube<f32>';
  44620. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44621. textureType = 'texture_2d_array<f32>';
  44622. } else if ( texture.isDepthTexture === true ) {
  44623. textureType = `texture_depth${multisampled}_2d`;
  44624. } else if ( texture.isVideoTexture === true ) {
  44625. textureType = 'texture_external';
  44626. } else if ( texture.isData3DTexture === true ) {
  44627. textureType = 'texture_3d<f32>';
  44628. } else if ( uniform.node.isStorageTextureNode === true ) {
  44629. const format = getFormat( texture );
  44630. const access = this.getStorageAccess( uniform.node, shaderStage );
  44631. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  44632. } else {
  44633. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  44634. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  44635. }
  44636. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  44637. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  44638. const bufferNode = uniform.node;
  44639. const bufferType = this.getType( bufferNode.bufferType );
  44640. const bufferCount = bufferNode.bufferCount;
  44641. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  44642. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  44643. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  44644. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  44645. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  44646. } else {
  44647. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  44648. const groupName = uniform.groupNode.name;
  44649. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  44650. index: uniformIndexes.binding ++,
  44651. id: uniformIndexes.group,
  44652. snippets: []
  44653. } );
  44654. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  44655. }
  44656. }
  44657. for ( const name in uniformGroups ) {
  44658. const group = uniformGroups[ name ];
  44659. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  44660. }
  44661. let code = bindingSnippets.join( '\n' );
  44662. code += bufferSnippets.join( '\n' );
  44663. code += structSnippets.join( '\n' );
  44664. return code;
  44665. }
  44666. /**
  44667. * Controls the code build of the shader stages.
  44668. */
  44669. buildCode() {
  44670. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44671. this.sortBindingGroups();
  44672. for ( const shaderStage in shadersData ) {
  44673. const stageData = shadersData[ shaderStage ];
  44674. stageData.uniforms = this.getUniforms( shaderStage );
  44675. stageData.attributes = this.getAttributes( shaderStage );
  44676. stageData.varyings = this.getVaryings( shaderStage );
  44677. stageData.structs = this.getStructs( shaderStage );
  44678. stageData.vars = this.getVars( shaderStage );
  44679. stageData.codes = this.getCodes( shaderStage );
  44680. stageData.directives = this.getDirectives( shaderStage );
  44681. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  44682. //
  44683. let flow = '// code\n\n';
  44684. flow += this.flowCode[ shaderStage ];
  44685. const flowNodes = this.flowNodes[ shaderStage ];
  44686. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44687. const outputNode = mainNode.outputNode;
  44688. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  44689. for ( const node of flowNodes ) {
  44690. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44691. const slotName = node.name;
  44692. if ( slotName ) {
  44693. if ( flow.length > 0 ) flow += '\n';
  44694. flow += `\t// flow -> ${ slotName }\n`;
  44695. }
  44696. flow += `${ flowSlotData.code }\n\t`;
  44697. if ( node === mainNode && shaderStage !== 'compute' ) {
  44698. flow += '// result\n\n\t';
  44699. if ( shaderStage === 'vertex' ) {
  44700. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  44701. } else if ( shaderStage === 'fragment' ) {
  44702. if ( isOutputStruct ) {
  44703. stageData.returnType = outputNode.nodeType;
  44704. flow += `return ${ flowSlotData.result };`;
  44705. } else {
  44706. let structSnippet = '\t@location(0) color: vec4<f32>';
  44707. const builtins = this.getBuiltins( 'output' );
  44708. if ( builtins ) structSnippet += ',\n\t' + builtins;
  44709. stageData.returnType = 'OutputStruct';
  44710. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  44711. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  44712. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  44713. }
  44714. }
  44715. }
  44716. }
  44717. stageData.flow = flow;
  44718. }
  44719. if ( this.material !== null ) {
  44720. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  44721. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  44722. } else {
  44723. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  44724. }
  44725. }
  44726. /**
  44727. * Returns the native shader method name for a given generic name.
  44728. *
  44729. * @param {String} method - The method name to resolve.
  44730. * @param {String} [output=null] - An optional output.
  44731. * @return {String} The resolved WGSL method name.
  44732. */
  44733. getMethod( method, output = null ) {
  44734. let wgslMethod;
  44735. if ( output !== null ) {
  44736. wgslMethod = this._getWGSLMethod( method + '_' + output );
  44737. }
  44738. if ( wgslMethod === undefined ) {
  44739. wgslMethod = this._getWGSLMethod( method );
  44740. }
  44741. return wgslMethod || method;
  44742. }
  44743. /**
  44744. * Returns the WGSL type of the given node data type.
  44745. *
  44746. * @param {String} type - The node data type.
  44747. * @return {String} The WGSL type.
  44748. */
  44749. getType( type ) {
  44750. return wgslTypeLib[ type ] || type;
  44751. }
  44752. /**
  44753. * Whether the requested feature is available or not.
  44754. *
  44755. * @param {String} name - The requested feature.
  44756. * @return {Boolean} Whether the requested feature is supported or not.
  44757. */
  44758. isAvailable( name ) {
  44759. let result = supports[ name ];
  44760. if ( result === undefined ) {
  44761. if ( name === 'float32Filterable' ) {
  44762. result = this.renderer.hasFeature( 'float32-filterable' );
  44763. } else if ( name === 'clipDistance' ) {
  44764. result = this.renderer.hasFeature( 'clip-distances' );
  44765. }
  44766. supports[ name ] = result;
  44767. }
  44768. return result;
  44769. }
  44770. /**
  44771. * Returns the native shader method name for a given generic name.
  44772. *
  44773. * @private
  44774. * @param {String} method - The method name to resolve.
  44775. * @return {String} The resolved WGSL method name.
  44776. */
  44777. _getWGSLMethod( method ) {
  44778. if ( wgslPolyfill[ method ] !== undefined ) {
  44779. this._include( method );
  44780. }
  44781. return wgslMethods[ method ];
  44782. }
  44783. /**
  44784. * Includes the given method name into the current
  44785. * function node.
  44786. *
  44787. * @private
  44788. * @param {String} name - The method name to include.
  44789. * @return {CodeNode} The respective code node.
  44790. */
  44791. _include( name ) {
  44792. const codeNode = wgslPolyfill[ name ];
  44793. codeNode.build( this );
  44794. if ( this.currentFunctionNode !== null ) {
  44795. this.currentFunctionNode.includes.push( codeNode );
  44796. }
  44797. return codeNode;
  44798. }
  44799. /**
  44800. * Returns a WGSL vertex shader based on the given shader data.
  44801. *
  44802. * @private
  44803. * @param {Object} shaderData - The shader data.
  44804. * @return {String} The vertex shader.
  44805. */
  44806. _getWGSLVertexCode( shaderData ) {
  44807. return `${ this.getSignature() }
  44808. // directives
  44809. ${shaderData.directives}
  44810. // uniforms
  44811. ${shaderData.uniforms}
  44812. // varyings
  44813. ${shaderData.varyings}
  44814. var<private> varyings : VaryingsStruct;
  44815. // codes
  44816. ${shaderData.codes}
  44817. @vertex
  44818. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  44819. // vars
  44820. ${shaderData.vars}
  44821. // flow
  44822. ${shaderData.flow}
  44823. return varyings;
  44824. }
  44825. `;
  44826. }
  44827. /**
  44828. * Returns a WGSL fragment shader based on the given shader data.
  44829. *
  44830. * @private
  44831. * @param {Object} shaderData - The shader data.
  44832. * @return {String} The vertex shader.
  44833. */
  44834. _getWGSLFragmentCode( shaderData ) {
  44835. return `${ this.getSignature() }
  44836. // global
  44837. ${ diagnostics }
  44838. // uniforms
  44839. ${shaderData.uniforms}
  44840. // structs
  44841. ${shaderData.structs}
  44842. // codes
  44843. ${shaderData.codes}
  44844. @fragment
  44845. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  44846. // vars
  44847. ${shaderData.vars}
  44848. // flow
  44849. ${shaderData.flow}
  44850. }
  44851. `;
  44852. }
  44853. /**
  44854. * Returns a WGSL compute shader based on the given shader data.
  44855. *
  44856. * @private
  44857. * @param {Object} shaderData - The shader data.
  44858. * @param {String} workgroupSize - The workgroup size.
  44859. * @return {String} The vertex shader.
  44860. */
  44861. _getWGSLComputeCode( shaderData, workgroupSize ) {
  44862. return `${ this.getSignature() }
  44863. // directives
  44864. ${shaderData.directives}
  44865. // system
  44866. var<private> instanceIndex : u32;
  44867. // locals
  44868. ${shaderData.scopedArrays}
  44869. // uniforms
  44870. ${shaderData.uniforms}
  44871. // codes
  44872. ${shaderData.codes}
  44873. @compute @workgroup_size( ${workgroupSize} )
  44874. fn main( ${shaderData.attributes} ) {
  44875. // system
  44876. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  44877. // vars
  44878. ${shaderData.vars}
  44879. // flow
  44880. ${shaderData.flow}
  44881. }
  44882. `;
  44883. }
  44884. /**
  44885. * Returns a WGSL struct based on the given name and variables.
  44886. *
  44887. * @private
  44888. * @param {String} name - The struct name.
  44889. * @param {String} vars - The struct variables.
  44890. * @return {String} The WGSL snippet representing a struct.
  44891. */
  44892. _getWGSLStruct( name, vars ) {
  44893. return `
  44894. struct ${name} {
  44895. ${vars}
  44896. };`;
  44897. }
  44898. /**
  44899. * Returns a WGSL struct binding.
  44900. *
  44901. * @private
  44902. * @param {String} name - The struct name.
  44903. * @param {String} vars - The struct variables.
  44904. * @param {String} access - The access.
  44905. * @param {Number} [binding=0] - The binding index.
  44906. * @param {Number} [group=0] - The group index.
  44907. * @return {String} The WGSL snippet representing a struct binding.
  44908. */
  44909. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  44910. const structName = name + 'Struct';
  44911. const structSnippet = this._getWGSLStruct( structName, vars );
  44912. return `${structSnippet}
  44913. @binding( ${binding} ) @group( ${group} )
  44914. var<${access}> ${name} : ${structName};`;
  44915. }
  44916. }
  44917. /**
  44918. * A WebGPU backend utility module with common helpers.
  44919. *
  44920. * @private
  44921. */
  44922. class WebGPUUtils {
  44923. /**
  44924. * Constructs a new utility object.
  44925. *
  44926. * @param {WebGPUBackend} backend - The WebGPU backend.
  44927. */
  44928. constructor( backend ) {
  44929. /**
  44930. * A reference to the WebGPU backend.
  44931. *
  44932. * @type {WebGPUBackend}
  44933. */
  44934. this.backend = backend;
  44935. }
  44936. /**
  44937. * Returns the depth/stencil GPU format for the given render context.
  44938. *
  44939. * @param {RenderContext} renderContext - The render context.
  44940. * @return {String} The depth/stencil GPU texture format.
  44941. */
  44942. getCurrentDepthStencilFormat( renderContext ) {
  44943. let format;
  44944. if ( renderContext.depthTexture !== null ) {
  44945. format = this.getTextureFormatGPU( renderContext.depthTexture );
  44946. } else if ( renderContext.depth && renderContext.stencil ) {
  44947. format = GPUTextureFormat.Depth24PlusStencil8;
  44948. } else if ( renderContext.depth ) {
  44949. format = GPUTextureFormat.Depth24Plus;
  44950. }
  44951. return format;
  44952. }
  44953. /**
  44954. * Returns the GPU format for the given texture.
  44955. *
  44956. * @param {Texture} texture - The texture.
  44957. * @return {String} The GPU texture format.
  44958. */
  44959. getTextureFormatGPU( texture ) {
  44960. return this.backend.get( texture ).format;
  44961. }
  44962. /**
  44963. * Returns an object that defines the multi-sampling state of the given texture.
  44964. *
  44965. * @param {Texture} texture - The texture.
  44966. * @return {Object} The multi-sampling state.
  44967. */
  44968. getTextureSampleData( texture ) {
  44969. let samples;
  44970. if ( texture.isFramebufferTexture ) {
  44971. samples = 1;
  44972. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  44973. const renderer = this.backend.renderer;
  44974. const renderTarget = renderer.getRenderTarget();
  44975. samples = renderTarget ? renderTarget.samples : renderer.samples;
  44976. } else if ( texture.renderTarget ) {
  44977. samples = texture.renderTarget.samples;
  44978. }
  44979. samples = samples || 1;
  44980. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  44981. const primarySamples = isMSAA ? 1 : samples;
  44982. return { samples, primarySamples, isMSAA };
  44983. }
  44984. /**
  44985. * Returns the default color attachment's GPU format of the current render context.
  44986. *
  44987. * @param {RenderContext} renderContext - The render context.
  44988. * @return {String} The GPU texture format of the default color attachment.
  44989. */
  44990. getCurrentColorFormat( renderContext ) {
  44991. let format;
  44992. if ( renderContext.textures !== null ) {
  44993. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  44994. } else {
  44995. format = this.getPreferredCanvasFormat(); // default context format
  44996. }
  44997. return format;
  44998. }
  44999. /**
  45000. * Returns the output color space of the current render context.
  45001. *
  45002. * @param {RenderContext} renderContext - The render context.
  45003. * @return {String} The output color space.
  45004. */
  45005. getCurrentColorSpace( renderContext ) {
  45006. if ( renderContext.textures !== null ) {
  45007. return renderContext.textures[ 0 ].colorSpace;
  45008. }
  45009. return this.backend.renderer.outputColorSpace;
  45010. }
  45011. /**
  45012. * Returns GPU primitive topology for the given object and material.
  45013. *
  45014. * @param {Object3D} object - The 3D object.
  45015. * @param {Material} material - The material.
  45016. * @return {String} The GPU primitive topology.
  45017. */
  45018. getPrimitiveTopology( object, material ) {
  45019. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  45020. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  45021. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  45022. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  45023. }
  45024. /**
  45025. * Returns a modified sample count from the given sample count value.
  45026. *
  45027. * That is required since WebGPU does not support arbitrary sample counts.
  45028. *
  45029. * @param {Number} sampleCount - The input sample count.
  45030. * @return {Number} The (potentially updated) output sample count.
  45031. */
  45032. getSampleCount( sampleCount ) {
  45033. let count = 1;
  45034. if ( sampleCount > 1 ) {
  45035. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  45036. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  45037. if ( count === 2 ) {
  45038. count = 4;
  45039. }
  45040. }
  45041. return count;
  45042. }
  45043. /**
  45044. * Returns the sample count of the given render context.
  45045. *
  45046. * @param {RenderContext} renderContext - The render context.
  45047. * @return {Number} The sample count.
  45048. */
  45049. getSampleCountRenderContext( renderContext ) {
  45050. if ( renderContext.textures !== null ) {
  45051. return this.getSampleCount( renderContext.sampleCount );
  45052. }
  45053. return this.getSampleCount( this.backend.renderer.samples );
  45054. }
  45055. /**
  45056. * Returns the preferred canvas format.
  45057. *
  45058. * There is a separate method for this so it's possible to
  45059. * honor edge cases for specific devices.
  45060. *
  45061. * @return {String} The GPU texture format of the canvas.
  45062. */
  45063. getPreferredCanvasFormat() {
  45064. const outputType = this.backend.parameters.outputType;
  45065. if ( outputType === undefined ) {
  45066. return navigator.gpu.getPreferredCanvasFormat();
  45067. } else if ( outputType === UnsignedByteType ) {
  45068. return GPUTextureFormat.BGRA8Unorm;
  45069. } else if ( outputType === HalfFloatType ) {
  45070. return GPUTextureFormat.RGBA16Float;
  45071. } else {
  45072. throw new Error( 'Unsupported outputType' );
  45073. }
  45074. }
  45075. }
  45076. const typedArraysToVertexFormatPrefix = new Map( [
  45077. [ Int8Array, [ 'sint8', 'snorm8' ]],
  45078. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  45079. [ Int16Array, [ 'sint16', 'snorm16' ]],
  45080. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  45081. [ Int32Array, [ 'sint32', 'snorm32' ]],
  45082. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  45083. [ Float32Array, [ 'float32', ]],
  45084. ] );
  45085. const typedAttributeToVertexFormatPrefix = new Map( [
  45086. [ Float16BufferAttribute, [ 'float16', ]],
  45087. ] );
  45088. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  45089. [ Int32Array, 'sint32' ],
  45090. [ Int16Array, 'sint32' ], // patch for INT16
  45091. [ Uint32Array, 'uint32' ],
  45092. [ Uint16Array, 'uint32' ], // patch for UINT16
  45093. [ Float32Array, 'float32' ]
  45094. ] );
  45095. /**
  45096. * A WebGPU backend utility module for managing shader attributes.
  45097. *
  45098. * @private
  45099. */
  45100. class WebGPUAttributeUtils {
  45101. /**
  45102. * Constructs a new utility object.
  45103. *
  45104. * @param {WebGPUBackend} backend - The WebGPU backend.
  45105. */
  45106. constructor( backend ) {
  45107. /**
  45108. * A reference to the WebGPU backend.
  45109. *
  45110. * @type {WebGPUBackend}
  45111. */
  45112. this.backend = backend;
  45113. }
  45114. /**
  45115. * Creates the GPU buffer for the given buffer attribute.
  45116. *
  45117. * @param {BufferAttribute} attribute - The buffer attribute.
  45118. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  45119. */
  45120. createAttribute( attribute, usage ) {
  45121. const bufferAttribute = this._getBufferAttribute( attribute );
  45122. const backend = this.backend;
  45123. const bufferData = backend.get( bufferAttribute );
  45124. let buffer = bufferData.buffer;
  45125. if ( buffer === undefined ) {
  45126. const device = backend.device;
  45127. let array = bufferAttribute.array;
  45128. // patch for INT16 and UINT16
  45129. if ( attribute.normalized === false ) {
  45130. if ( array.constructor === Int16Array ) {
  45131. array = new Int32Array( array );
  45132. } else if ( array.constructor === Uint16Array ) {
  45133. array = new Uint32Array( array );
  45134. if ( usage & GPUBufferUsage.INDEX ) {
  45135. for ( let i = 0; i < array.length; i ++ ) {
  45136. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  45137. }
  45138. }
  45139. }
  45140. }
  45141. bufferAttribute.array = array;
  45142. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  45143. array = new array.constructor( bufferAttribute.count * 4 );
  45144. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  45145. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  45146. }
  45147. // Update BufferAttribute
  45148. bufferAttribute.itemSize = 4;
  45149. bufferAttribute.array = array;
  45150. }
  45151. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  45152. buffer = device.createBuffer( {
  45153. label: bufferAttribute.name,
  45154. size: size,
  45155. usage: usage,
  45156. mappedAtCreation: true
  45157. } );
  45158. new array.constructor( buffer.getMappedRange() ).set( array );
  45159. buffer.unmap();
  45160. bufferData.buffer = buffer;
  45161. }
  45162. }
  45163. /**
  45164. * Updates the GPU buffer of the given buffer attribute.
  45165. *
  45166. * @param {BufferAttribute} attribute - The buffer attribute.
  45167. */
  45168. updateAttribute( attribute ) {
  45169. const bufferAttribute = this._getBufferAttribute( attribute );
  45170. const backend = this.backend;
  45171. const device = backend.device;
  45172. const buffer = backend.get( bufferAttribute ).buffer;
  45173. const array = bufferAttribute.array;
  45174. const isTypedArray = this._isTypedArray( array );
  45175. const updateRanges = bufferAttribute.updateRanges;
  45176. if ( updateRanges.length === 0 ) {
  45177. // Not using update ranges
  45178. device.queue.writeBuffer(
  45179. buffer,
  45180. 0,
  45181. array,
  45182. 0
  45183. );
  45184. } else {
  45185. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  45186. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45187. const range = updateRanges[ i ];
  45188. const dataOffset = range.start * byteOffsetFactor;
  45189. const size = range.count * byteOffsetFactor;
  45190. device.queue.writeBuffer(
  45191. buffer,
  45192. 0,
  45193. array,
  45194. dataOffset,
  45195. size
  45196. );
  45197. }
  45198. bufferAttribute.clearUpdateRanges();
  45199. }
  45200. }
  45201. /**
  45202. * This method creates the vertex buffer layout data which are
  45203. * require when creating a render pipeline for the given render object.
  45204. *
  45205. * @param {RenderObject} renderObject - The render object.
  45206. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  45207. */
  45208. createShaderVertexBuffers( renderObject ) {
  45209. const attributes = renderObject.getAttributes();
  45210. const vertexBuffers = new Map();
  45211. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  45212. const geometryAttribute = attributes[ slot ];
  45213. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  45214. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  45215. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  45216. if ( vertexBufferLayout === undefined ) {
  45217. let arrayStride, stepMode;
  45218. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  45219. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  45220. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45221. } else {
  45222. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  45223. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45224. }
  45225. // patch for INT16 and UINT16
  45226. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  45227. arrayStride = 4;
  45228. }
  45229. vertexBufferLayout = {
  45230. arrayStride,
  45231. attributes: [],
  45232. stepMode
  45233. };
  45234. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  45235. }
  45236. const format = this._getVertexFormat( geometryAttribute );
  45237. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  45238. vertexBufferLayout.attributes.push( {
  45239. shaderLocation: slot,
  45240. offset,
  45241. format
  45242. } );
  45243. }
  45244. return Array.from( vertexBuffers.values() );
  45245. }
  45246. /**
  45247. * Destroys the GPU buffer of the given buffer attribute.
  45248. *
  45249. * @param {BufferAttribute} attribute - The buffer attribute.
  45250. */
  45251. destroyAttribute( attribute ) {
  45252. const backend = this.backend;
  45253. const data = backend.get( this._getBufferAttribute( attribute ) );
  45254. data.buffer.destroy();
  45255. backend.delete( attribute );
  45256. }
  45257. /**
  45258. * This method performs a readback operation by moving buffer data from
  45259. * a storage buffer attribute from the GPU to the CPU.
  45260. *
  45261. * @async
  45262. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45263. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45264. */
  45265. async getArrayBufferAsync( attribute ) {
  45266. const backend = this.backend;
  45267. const device = backend.device;
  45268. const data = backend.get( this._getBufferAttribute( attribute ) );
  45269. const bufferGPU = data.buffer;
  45270. const size = bufferGPU.size;
  45271. const readBufferGPU = device.createBuffer( {
  45272. label: `${ attribute.name }_readback`,
  45273. size,
  45274. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45275. } );
  45276. const cmdEncoder = device.createCommandEncoder( {
  45277. label: `readback_encoder_${ attribute.name }`
  45278. } );
  45279. cmdEncoder.copyBufferToBuffer(
  45280. bufferGPU,
  45281. 0,
  45282. readBufferGPU,
  45283. 0,
  45284. size
  45285. );
  45286. const gpuCommands = cmdEncoder.finish();
  45287. device.queue.submit( [ gpuCommands ] );
  45288. await readBufferGPU.mapAsync( GPUMapMode.READ );
  45289. const arrayBuffer = readBufferGPU.getMappedRange();
  45290. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  45291. readBufferGPU.unmap();
  45292. return dstBuffer.buffer;
  45293. }
  45294. /**
  45295. * Returns the vertex format of the given buffer attribute.
  45296. *
  45297. * @private
  45298. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  45299. * @return {String} The vertex format (e.g. 'float32x3').
  45300. */
  45301. _getVertexFormat( geometryAttribute ) {
  45302. const { itemSize, normalized } = geometryAttribute;
  45303. const ArrayType = geometryAttribute.array.constructor;
  45304. const AttributeType = geometryAttribute.constructor;
  45305. let format;
  45306. if ( itemSize === 1 ) {
  45307. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  45308. } else {
  45309. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  45310. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  45311. if ( prefix ) {
  45312. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  45313. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  45314. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  45315. if ( paddedItemSize % 1 ) {
  45316. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  45317. }
  45318. format = `${prefix}x${paddedItemSize}`;
  45319. }
  45320. }
  45321. if ( ! format ) {
  45322. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  45323. }
  45324. return format;
  45325. }
  45326. /**
  45327. * Returns `true` if the given array is a typed array.
  45328. *
  45329. * @private
  45330. * @param {Any} array - The array.
  45331. * @return {Boolean} Whether the given array is a typed array or not.
  45332. */
  45333. _isTypedArray( array ) {
  45334. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  45335. }
  45336. /**
  45337. * Utility method for handling interleaved buffer attributes correctly.
  45338. * To process them, their `InterleavedBuffer` is returned.
  45339. *
  45340. * @private
  45341. * @param {BufferAttribute} attribute - The attribute.
  45342. * @return {BufferAttribute|InterleavedBuffer}
  45343. */
  45344. _getBufferAttribute( attribute ) {
  45345. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  45346. return attribute;
  45347. }
  45348. }
  45349. /**
  45350. * A WebGPU backend utility module for managing bindings.
  45351. *
  45352. * When reading the documentation it's helpful to keep in mind that
  45353. * all class definitions starting with 'GPU*' are modules from the
  45354. * WebGPU API. So for example `BindGroup` is a class from the engine
  45355. * whereas `GPUBindGroup` is a class from WebGPU.
  45356. *
  45357. * @private
  45358. */
  45359. class WebGPUBindingUtils {
  45360. /**
  45361. * Constructs a new utility object.
  45362. *
  45363. * @param {WebGPUBackend} backend - The WebGPU backend.
  45364. */
  45365. constructor( backend ) {
  45366. /**
  45367. * A reference to the WebGPU backend.
  45368. *
  45369. * @type {WebGPUBackend}
  45370. */
  45371. this.backend = backend;
  45372. /**
  45373. * A cache for managing bind group layouts.
  45374. *
  45375. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  45376. */
  45377. this.bindGroupLayoutCache = new WeakMap();
  45378. }
  45379. /**
  45380. * Creates a GPU bind group layout for the given bind group.
  45381. *
  45382. * @param {BindGroup} bindGroup - The bind group.
  45383. * @return {GPUBindGroupLayout} The GPU bind group layout.
  45384. */
  45385. createBindingsLayout( bindGroup ) {
  45386. const backend = this.backend;
  45387. const device = backend.device;
  45388. const entries = [];
  45389. let index = 0;
  45390. for ( const binding of bindGroup.bindings ) {
  45391. const bindingGPU = {
  45392. binding: index ++,
  45393. visibility: binding.visibility
  45394. };
  45395. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45396. const buffer = {}; // GPUBufferBindingLayout
  45397. if ( binding.isStorageBuffer ) {
  45398. if ( binding.visibility & 4 ) {
  45399. // compute
  45400. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  45401. buffer.type = GPUBufferBindingType.Storage;
  45402. } else {
  45403. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45404. }
  45405. } else {
  45406. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45407. }
  45408. }
  45409. bindingGPU.buffer = buffer;
  45410. } else if ( binding.isSampler ) {
  45411. const sampler = {}; // GPUSamplerBindingLayout
  45412. if ( binding.texture.isDepthTexture ) {
  45413. if ( binding.texture.compareFunction !== null ) {
  45414. sampler.type = 'comparison';
  45415. }
  45416. }
  45417. bindingGPU.sampler = sampler;
  45418. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45419. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45420. } else if ( binding.isSampledTexture && binding.store ) {
  45421. const storageTexture = {}; // GPUStorageTextureBindingLayout
  45422. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  45423. const access = binding.access;
  45424. if ( access === NodeAccess.READ_WRITE ) {
  45425. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  45426. } else if ( access === NodeAccess.WRITE_ONLY ) {
  45427. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  45428. } else {
  45429. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  45430. }
  45431. bindingGPU.storageTexture = storageTexture;
  45432. } else if ( binding.isSampledTexture ) {
  45433. const texture = {}; // GPUTextureBindingLayout
  45434. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  45435. if ( primarySamples > 1 ) {
  45436. texture.multisampled = true;
  45437. if ( ! binding.texture.isDepthTexture ) {
  45438. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45439. }
  45440. }
  45441. if ( binding.texture.isDepthTexture ) {
  45442. texture.sampleType = GPUTextureSampleType.Depth;
  45443. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  45444. const type = binding.texture.type;
  45445. if ( type === IntType ) {
  45446. texture.sampleType = GPUTextureSampleType.SInt;
  45447. } else if ( type === UnsignedIntType ) {
  45448. texture.sampleType = GPUTextureSampleType.UInt;
  45449. } else if ( type === FloatType ) {
  45450. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  45451. texture.sampleType = GPUTextureSampleType.Float;
  45452. } else {
  45453. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45454. }
  45455. }
  45456. }
  45457. if ( binding.isSampledCubeTexture ) {
  45458. texture.viewDimension = GPUTextureViewDimension.Cube;
  45459. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45460. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  45461. } else if ( binding.isSampledTexture3D ) {
  45462. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  45463. }
  45464. bindingGPU.texture = texture;
  45465. } else {
  45466. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  45467. }
  45468. entries.push( bindingGPU );
  45469. }
  45470. return device.createBindGroupLayout( { entries } );
  45471. }
  45472. /**
  45473. * Creates bindings from the given bind group definition.
  45474. *
  45475. * @param {BindGroup} bindGroup - The bind group.
  45476. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45477. * @param {Number} cacheIndex - The cache index.
  45478. * @param {Number} version - The version.
  45479. */
  45480. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  45481. const { backend, bindGroupLayoutCache } = this;
  45482. const bindingsData = backend.get( bindGroup );
  45483. // setup (static) binding layout and (dynamic) binding group
  45484. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  45485. if ( bindLayoutGPU === undefined ) {
  45486. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  45487. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  45488. }
  45489. let bindGroupGPU;
  45490. if ( cacheIndex > 0 ) {
  45491. if ( bindingsData.groups === undefined ) {
  45492. bindingsData.groups = [];
  45493. bindingsData.versions = [];
  45494. }
  45495. if ( bindingsData.versions[ cacheIndex ] === version ) {
  45496. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  45497. }
  45498. }
  45499. if ( bindGroupGPU === undefined ) {
  45500. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  45501. if ( cacheIndex > 0 ) {
  45502. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  45503. bindingsData.versions[ cacheIndex ] = version;
  45504. }
  45505. }
  45506. bindingsData.group = bindGroupGPU;
  45507. bindingsData.layout = bindLayoutGPU;
  45508. }
  45509. /**
  45510. * Updates a buffer binding.
  45511. *
  45512. * @param {Buffer} binding - The buffer binding to update.
  45513. */
  45514. updateBinding( binding ) {
  45515. const backend = this.backend;
  45516. const device = backend.device;
  45517. const buffer = binding.buffer;
  45518. const bufferGPU = backend.get( binding ).buffer;
  45519. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  45520. }
  45521. /**
  45522. * Creates a GPU bind group for the camera index.
  45523. *
  45524. * @param {Uint32Array} data - The index data.
  45525. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  45526. * @return {GPUBindGroup} The GPU bind group.
  45527. */
  45528. createBindGroupIndex( data, layout ) {
  45529. const backend = this.backend;
  45530. const device = backend.device;
  45531. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45532. const index = data[ 0 ];
  45533. const buffer = device.createBuffer( {
  45534. label: 'bindingCameraIndex_' + index,
  45535. size: 16, // uint(4) * 4
  45536. usage: usage
  45537. } );
  45538. device.queue.writeBuffer( buffer, 0, data, 0 );
  45539. const entries = [ { binding: 0, resource: { buffer } } ];
  45540. return device.createBindGroup( {
  45541. label: 'bindGroupCameraIndex_' + index,
  45542. layout,
  45543. entries
  45544. } );
  45545. }
  45546. /**
  45547. * Creates a GPU bind group for the given bind group and GPU layout.
  45548. *
  45549. * @param {BindGroup} bindGroup - The bind group.
  45550. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  45551. * @return {GPUBindGroup} The GPU bind group.
  45552. */
  45553. createBindGroup( bindGroup, layoutGPU ) {
  45554. const backend = this.backend;
  45555. const device = backend.device;
  45556. let bindingPoint = 0;
  45557. const entriesGPU = [];
  45558. for ( const binding of bindGroup.bindings ) {
  45559. if ( binding.isUniformBuffer ) {
  45560. const bindingData = backend.get( binding );
  45561. if ( bindingData.buffer === undefined ) {
  45562. const byteLength = binding.byteLength;
  45563. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45564. const bufferGPU = device.createBuffer( {
  45565. label: 'bindingBuffer_' + binding.name,
  45566. size: byteLength,
  45567. usage: usage
  45568. } );
  45569. bindingData.buffer = bufferGPU;
  45570. }
  45571. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45572. } else if ( binding.isStorageBuffer ) {
  45573. const bindingData = backend.get( binding );
  45574. if ( bindingData.buffer === undefined ) {
  45575. const attribute = binding.attribute;
  45576. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  45577. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  45578. bindingData.buffer = backend.get( attribute ).buffer;
  45579. }
  45580. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45581. } else if ( binding.isSampler ) {
  45582. const textureGPU = backend.get( binding.texture );
  45583. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  45584. } else if ( binding.isSampledTexture ) {
  45585. const textureData = backend.get( binding.texture );
  45586. let resourceGPU;
  45587. if ( textureData.externalTexture !== undefined ) {
  45588. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  45589. } else {
  45590. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  45591. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  45592. resourceGPU = textureData[ propertyName ];
  45593. if ( resourceGPU === undefined ) {
  45594. const aspectGPU = GPUTextureAspect.All;
  45595. let dimensionViewGPU;
  45596. if ( binding.isSampledCubeTexture ) {
  45597. dimensionViewGPU = GPUTextureViewDimension.Cube;
  45598. } else if ( binding.isSampledTexture3D ) {
  45599. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  45600. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45601. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  45602. } else {
  45603. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  45604. }
  45605. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  45606. }
  45607. }
  45608. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  45609. }
  45610. bindingPoint ++;
  45611. }
  45612. return device.createBindGroup( {
  45613. label: 'bindGroup_' + bindGroup.name,
  45614. layout: layoutGPU,
  45615. entries: entriesGPU
  45616. } );
  45617. }
  45618. }
  45619. /**
  45620. * A WebGPU backend utility module for managing pipelines.
  45621. *
  45622. * @private
  45623. */
  45624. class WebGPUPipelineUtils {
  45625. /**
  45626. * Constructs a new utility object.
  45627. *
  45628. * @param {WebGPUBackend} backend - The WebGPU backend.
  45629. */
  45630. constructor( backend ) {
  45631. /**
  45632. * A reference to the WebGPU backend.
  45633. *
  45634. * @type {WebGPUBackend}
  45635. */
  45636. this.backend = backend;
  45637. }
  45638. /**
  45639. * Returns the sample count derived from the given render context.
  45640. *
  45641. * @private
  45642. * @param {RenderContext} renderContext - The render context.
  45643. * @return {Number} The sample count.
  45644. */
  45645. _getSampleCount( renderContext ) {
  45646. return this.backend.utils.getSampleCountRenderContext( renderContext );
  45647. }
  45648. /**
  45649. * Creates a render pipeline for the given render object.
  45650. *
  45651. * @param {RenderObject} renderObject - The render object.
  45652. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45653. */
  45654. createRenderPipeline( renderObject, promises ) {
  45655. const { object, material, geometry, pipeline } = renderObject;
  45656. const { vertexProgram, fragmentProgram } = pipeline;
  45657. const backend = this.backend;
  45658. const device = backend.device;
  45659. const utils = backend.utils;
  45660. const pipelineData = backend.get( pipeline );
  45661. // bind group layouts
  45662. const bindGroupLayouts = [];
  45663. for ( const bindGroup of renderObject.getBindings() ) {
  45664. const bindingsData = backend.get( bindGroup );
  45665. bindGroupLayouts.push( bindingsData.layout );
  45666. }
  45667. // vertex buffers
  45668. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  45669. // blending
  45670. let blending;
  45671. if ( material.transparent === true && material.blending !== NoBlending ) {
  45672. blending = this._getBlending( material );
  45673. }
  45674. // stencil
  45675. let stencilFront = {};
  45676. if ( material.stencilWrite === true ) {
  45677. stencilFront = {
  45678. compare: this._getStencilCompare( material ),
  45679. failOp: this._getStencilOperation( material.stencilFail ),
  45680. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  45681. passOp: this._getStencilOperation( material.stencilZPass )
  45682. };
  45683. }
  45684. const colorWriteMask = this._getColorWriteMask( material );
  45685. const targets = [];
  45686. if ( renderObject.context.textures !== null ) {
  45687. const textures = renderObject.context.textures;
  45688. for ( let i = 0; i < textures.length; i ++ ) {
  45689. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  45690. targets.push( {
  45691. format: colorFormat,
  45692. blend: blending,
  45693. writeMask: colorWriteMask
  45694. } );
  45695. }
  45696. } else {
  45697. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45698. targets.push( {
  45699. format: colorFormat,
  45700. blend: blending,
  45701. writeMask: colorWriteMask
  45702. } );
  45703. }
  45704. const vertexModule = backend.get( vertexProgram ).module;
  45705. const fragmentModule = backend.get( fragmentProgram ).module;
  45706. const primitiveState = this._getPrimitiveState( object, geometry, material );
  45707. const depthCompare = this._getDepthCompare( material );
  45708. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45709. const sampleCount = this._getSampleCount( renderObject.context );
  45710. const pipelineDescriptor = {
  45711. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  45712. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  45713. fragment: Object.assign( {}, fragmentModule, { targets } ),
  45714. primitive: primitiveState,
  45715. multisample: {
  45716. count: sampleCount,
  45717. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  45718. },
  45719. layout: device.createPipelineLayout( {
  45720. bindGroupLayouts
  45721. } )
  45722. };
  45723. const depthStencil = {};
  45724. const renderDepth = renderObject.context.depth;
  45725. const renderStencil = renderObject.context.stencil;
  45726. if ( renderDepth === true || renderStencil === true ) {
  45727. if ( renderDepth === true ) {
  45728. depthStencil.format = depthStencilFormat;
  45729. depthStencil.depthWriteEnabled = material.depthWrite;
  45730. depthStencil.depthCompare = depthCompare;
  45731. }
  45732. if ( renderStencil === true ) {
  45733. depthStencil.stencilFront = stencilFront;
  45734. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  45735. depthStencil.stencilReadMask = material.stencilFuncMask;
  45736. depthStencil.stencilWriteMask = material.stencilWriteMask;
  45737. }
  45738. pipelineDescriptor.depthStencil = depthStencil;
  45739. }
  45740. if ( promises === null ) {
  45741. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  45742. } else {
  45743. const p = new Promise( ( resolve /*, reject*/ ) => {
  45744. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  45745. pipelineData.pipeline = pipeline;
  45746. resolve();
  45747. } );
  45748. } );
  45749. promises.push( p );
  45750. }
  45751. }
  45752. /**
  45753. * Creates GPU render bundle encoder for the given render context.
  45754. *
  45755. * @param {RenderContext} renderContext - The render context.
  45756. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  45757. */
  45758. createBundleEncoder( renderContext ) {
  45759. const backend = this.backend;
  45760. const { utils, device } = backend;
  45761. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  45762. const colorFormat = utils.getCurrentColorFormat( renderContext );
  45763. const sampleCount = this._getSampleCount( renderContext );
  45764. const descriptor = {
  45765. label: 'renderBundleEncoder',
  45766. colorFormats: [ colorFormat ],
  45767. depthStencilFormat,
  45768. sampleCount
  45769. };
  45770. return device.createRenderBundleEncoder( descriptor );
  45771. }
  45772. /**
  45773. * Creates a compute pipeline for the given compute node.
  45774. *
  45775. * @param {ComputePipeline} pipeline - The compute pipeline.
  45776. * @param {Array<BindGroup>} bindings - The bindings.
  45777. */
  45778. createComputePipeline( pipeline, bindings ) {
  45779. const backend = this.backend;
  45780. const device = backend.device;
  45781. const computeProgram = backend.get( pipeline.computeProgram ).module;
  45782. const pipelineGPU = backend.get( pipeline );
  45783. // bind group layouts
  45784. const bindGroupLayouts = [];
  45785. for ( const bindingsGroup of bindings ) {
  45786. const bindingsData = backend.get( bindingsGroup );
  45787. bindGroupLayouts.push( bindingsData.layout );
  45788. }
  45789. pipelineGPU.pipeline = device.createComputePipeline( {
  45790. compute: computeProgram,
  45791. layout: device.createPipelineLayout( {
  45792. bindGroupLayouts
  45793. } )
  45794. } );
  45795. }
  45796. /**
  45797. * Returns the blending state as a descriptor object required
  45798. * for the pipeline creation.
  45799. *
  45800. * @private
  45801. * @param {Material} material - The material.
  45802. * @return {Object} The blending state.
  45803. */
  45804. _getBlending( material ) {
  45805. let color, alpha;
  45806. const blending = material.blending;
  45807. const blendSrc = material.blendSrc;
  45808. const blendDst = material.blendDst;
  45809. const blendEquation = material.blendEquation;
  45810. if ( blending === CustomBlending ) {
  45811. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  45812. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  45813. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  45814. color = {
  45815. srcFactor: this._getBlendFactor( blendSrc ),
  45816. dstFactor: this._getBlendFactor( blendDst ),
  45817. operation: this._getBlendOperation( blendEquation )
  45818. };
  45819. alpha = {
  45820. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  45821. dstFactor: this._getBlendFactor( blendDstAlpha ),
  45822. operation: this._getBlendOperation( blendEquationAlpha )
  45823. };
  45824. } else {
  45825. const premultipliedAlpha = material.premultipliedAlpha;
  45826. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  45827. color = {
  45828. srcFactor: srcRGB,
  45829. dstFactor: dstRGB,
  45830. operation: GPUBlendOperation.Add
  45831. };
  45832. alpha = {
  45833. srcFactor: srcAlpha,
  45834. dstFactor: dstAlpha,
  45835. operation: GPUBlendOperation.Add
  45836. };
  45837. };
  45838. if ( premultipliedAlpha ) {
  45839. switch ( blending ) {
  45840. case NormalBlending:
  45841. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45842. break;
  45843. case AdditiveBlending:
  45844. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  45845. break;
  45846. case SubtractiveBlending:
  45847. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45848. break;
  45849. case MultiplyBlending:
  45850. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  45851. break;
  45852. }
  45853. } else {
  45854. switch ( blending ) {
  45855. case NormalBlending:
  45856. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45857. break;
  45858. case AdditiveBlending:
  45859. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  45860. break;
  45861. case SubtractiveBlending:
  45862. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45863. break;
  45864. case MultiplyBlending:
  45865. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  45866. break;
  45867. }
  45868. }
  45869. }
  45870. if ( color !== undefined && alpha !== undefined ) {
  45871. return { color, alpha };
  45872. } else {
  45873. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  45874. }
  45875. }
  45876. /**
  45877. * Returns the GPU blend factor which is required for the pipeline creation.
  45878. *
  45879. * @private
  45880. * @param {Number} blend - The blend factor as a three.js constant.
  45881. * @return {String} The GPU blend factor.
  45882. */
  45883. _getBlendFactor( blend ) {
  45884. let blendFactor;
  45885. switch ( blend ) {
  45886. case ZeroFactor:
  45887. blendFactor = GPUBlendFactor.Zero;
  45888. break;
  45889. case OneFactor:
  45890. blendFactor = GPUBlendFactor.One;
  45891. break;
  45892. case SrcColorFactor:
  45893. blendFactor = GPUBlendFactor.Src;
  45894. break;
  45895. case OneMinusSrcColorFactor:
  45896. blendFactor = GPUBlendFactor.OneMinusSrc;
  45897. break;
  45898. case SrcAlphaFactor:
  45899. blendFactor = GPUBlendFactor.SrcAlpha;
  45900. break;
  45901. case OneMinusSrcAlphaFactor:
  45902. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  45903. break;
  45904. case DstColorFactor:
  45905. blendFactor = GPUBlendFactor.Dst;
  45906. break;
  45907. case OneMinusDstColorFactor:
  45908. blendFactor = GPUBlendFactor.OneMinusDstColor;
  45909. break;
  45910. case DstAlphaFactor:
  45911. blendFactor = GPUBlendFactor.DstAlpha;
  45912. break;
  45913. case OneMinusDstAlphaFactor:
  45914. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  45915. break;
  45916. case SrcAlphaSaturateFactor:
  45917. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  45918. break;
  45919. case BlendColorFactor:
  45920. blendFactor = GPUBlendFactor.Constant;
  45921. break;
  45922. case OneMinusBlendColorFactor:
  45923. blendFactor = GPUBlendFactor.OneMinusConstant;
  45924. break;
  45925. default:
  45926. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  45927. }
  45928. return blendFactor;
  45929. }
  45930. /**
  45931. * Returns the GPU stencil compare function which is required for the pipeline creation.
  45932. *
  45933. * @private
  45934. * @param {Material} material - The material.
  45935. * @return {String} The GPU stencil compare function.
  45936. */
  45937. _getStencilCompare( material ) {
  45938. let stencilCompare;
  45939. const stencilFunc = material.stencilFunc;
  45940. switch ( stencilFunc ) {
  45941. case NeverStencilFunc:
  45942. stencilCompare = GPUCompareFunction.Never;
  45943. break;
  45944. case AlwaysStencilFunc:
  45945. stencilCompare = GPUCompareFunction.Always;
  45946. break;
  45947. case LessStencilFunc:
  45948. stencilCompare = GPUCompareFunction.Less;
  45949. break;
  45950. case LessEqualStencilFunc:
  45951. stencilCompare = GPUCompareFunction.LessEqual;
  45952. break;
  45953. case EqualStencilFunc:
  45954. stencilCompare = GPUCompareFunction.Equal;
  45955. break;
  45956. case GreaterEqualStencilFunc:
  45957. stencilCompare = GPUCompareFunction.GreaterEqual;
  45958. break;
  45959. case GreaterStencilFunc:
  45960. stencilCompare = GPUCompareFunction.Greater;
  45961. break;
  45962. case NotEqualStencilFunc:
  45963. stencilCompare = GPUCompareFunction.NotEqual;
  45964. break;
  45965. default:
  45966. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  45967. }
  45968. return stencilCompare;
  45969. }
  45970. /**
  45971. * Returns the GPU stencil operation which is required for the pipeline creation.
  45972. *
  45973. * @private
  45974. * @param {Number} op - A three.js constant defining the stencil operation.
  45975. * @return {String} The GPU stencil operation.
  45976. */
  45977. _getStencilOperation( op ) {
  45978. let stencilOperation;
  45979. switch ( op ) {
  45980. case KeepStencilOp:
  45981. stencilOperation = GPUStencilOperation.Keep;
  45982. break;
  45983. case ZeroStencilOp:
  45984. stencilOperation = GPUStencilOperation.Zero;
  45985. break;
  45986. case ReplaceStencilOp:
  45987. stencilOperation = GPUStencilOperation.Replace;
  45988. break;
  45989. case InvertStencilOp:
  45990. stencilOperation = GPUStencilOperation.Invert;
  45991. break;
  45992. case IncrementStencilOp:
  45993. stencilOperation = GPUStencilOperation.IncrementClamp;
  45994. break;
  45995. case DecrementStencilOp:
  45996. stencilOperation = GPUStencilOperation.DecrementClamp;
  45997. break;
  45998. case IncrementWrapStencilOp:
  45999. stencilOperation = GPUStencilOperation.IncrementWrap;
  46000. break;
  46001. case DecrementWrapStencilOp:
  46002. stencilOperation = GPUStencilOperation.DecrementWrap;
  46003. break;
  46004. default:
  46005. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  46006. }
  46007. return stencilOperation;
  46008. }
  46009. /**
  46010. * Returns the GPU blend operation which is required for the pipeline creation.
  46011. *
  46012. * @private
  46013. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  46014. * @return {String} The GPU blend operation.
  46015. */
  46016. _getBlendOperation( blendEquation ) {
  46017. let blendOperation;
  46018. switch ( blendEquation ) {
  46019. case AddEquation:
  46020. blendOperation = GPUBlendOperation.Add;
  46021. break;
  46022. case SubtractEquation:
  46023. blendOperation = GPUBlendOperation.Subtract;
  46024. break;
  46025. case ReverseSubtractEquation:
  46026. blendOperation = GPUBlendOperation.ReverseSubtract;
  46027. break;
  46028. case MinEquation:
  46029. blendOperation = GPUBlendOperation.Min;
  46030. break;
  46031. case MaxEquation:
  46032. blendOperation = GPUBlendOperation.Max;
  46033. break;
  46034. default:
  46035. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  46036. }
  46037. return blendOperation;
  46038. }
  46039. /**
  46040. * Returns the primitive state as a descriptor object required
  46041. * for the pipeline creation.
  46042. *
  46043. * @private
  46044. * @param {Object3D} object - The 3D object.
  46045. * @param {BufferGeometry} geometry - The geometry.
  46046. * @param {Material} material - The material.
  46047. * @return {Object} The primitive state.
  46048. */
  46049. _getPrimitiveState( object, geometry, material ) {
  46050. const descriptor = {};
  46051. const utils = this.backend.utils;
  46052. descriptor.topology = utils.getPrimitiveTopology( object, material );
  46053. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  46054. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46055. }
  46056. switch ( material.side ) {
  46057. case FrontSide:
  46058. descriptor.frontFace = GPUFrontFace.CCW;
  46059. descriptor.cullMode = GPUCullMode.Back;
  46060. break;
  46061. case BackSide:
  46062. descriptor.frontFace = GPUFrontFace.CCW;
  46063. descriptor.cullMode = GPUCullMode.Front;
  46064. break;
  46065. case DoubleSide:
  46066. descriptor.frontFace = GPUFrontFace.CCW;
  46067. descriptor.cullMode = GPUCullMode.None;
  46068. break;
  46069. default:
  46070. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  46071. break;
  46072. }
  46073. return descriptor;
  46074. }
  46075. /**
  46076. * Returns the GPU color write mask which is required for the pipeline creation.
  46077. *
  46078. * @private
  46079. * @param {Material} material - The material.
  46080. * @return {String} The GPU color write mask.
  46081. */
  46082. _getColorWriteMask( material ) {
  46083. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  46084. }
  46085. /**
  46086. * Returns the GPU depth compare function which is required for the pipeline creation.
  46087. *
  46088. * @private
  46089. * @param {Material} material - The material.
  46090. * @return {String} The GPU depth compare function.
  46091. */
  46092. _getDepthCompare( material ) {
  46093. let depthCompare;
  46094. if ( material.depthTest === false ) {
  46095. depthCompare = GPUCompareFunction.Always;
  46096. } else {
  46097. const depthFunc = material.depthFunc;
  46098. switch ( depthFunc ) {
  46099. case NeverDepth:
  46100. depthCompare = GPUCompareFunction.Never;
  46101. break;
  46102. case AlwaysDepth:
  46103. depthCompare = GPUCompareFunction.Always;
  46104. break;
  46105. case LessDepth:
  46106. depthCompare = GPUCompareFunction.Less;
  46107. break;
  46108. case LessEqualDepth:
  46109. depthCompare = GPUCompareFunction.LessEqual;
  46110. break;
  46111. case EqualDepth:
  46112. depthCompare = GPUCompareFunction.Equal;
  46113. break;
  46114. case GreaterEqualDepth:
  46115. depthCompare = GPUCompareFunction.GreaterEqual;
  46116. break;
  46117. case GreaterDepth:
  46118. depthCompare = GPUCompareFunction.Greater;
  46119. break;
  46120. case NotEqualDepth:
  46121. depthCompare = GPUCompareFunction.NotEqual;
  46122. break;
  46123. default:
  46124. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  46125. }
  46126. }
  46127. return depthCompare;
  46128. }
  46129. }
  46130. /*// debugger tools
  46131. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  46132. //*/
  46133. /**
  46134. * A backend implementation targeting WebGPU.
  46135. *
  46136. * @private
  46137. * @augments Backend
  46138. */
  46139. class WebGPUBackend extends Backend {
  46140. /**
  46141. * Constructs a new WebGPU backend.
  46142. *
  46143. * @param {Object} parameters - The configuration parameter.
  46144. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46145. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46146. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46147. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46148. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46149. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  46150. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46151. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  46152. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  46153. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  46154. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  46155. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  46156. */
  46157. constructor( parameters = {} ) {
  46158. super( parameters );
  46159. /**
  46160. * This flag can be used for type testing.
  46161. *
  46162. * @type {Boolean}
  46163. * @readonly
  46164. * @default true
  46165. */
  46166. this.isWebGPUBackend = true;
  46167. // some parameters require default values other than "undefined"
  46168. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  46169. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  46170. /**
  46171. * Whether to track timestamps with a Timestamp Query API or not.
  46172. *
  46173. * @type {Boolean}
  46174. * @default false
  46175. */
  46176. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46177. /**
  46178. * A reference to the device.
  46179. *
  46180. * @type {GPUDevice?}
  46181. * @default null
  46182. */
  46183. this.device = null;
  46184. /**
  46185. * A reference to the context.
  46186. *
  46187. * @type {GPUCanvasContext?}
  46188. * @default null
  46189. */
  46190. this.context = null;
  46191. /**
  46192. * A reference to the color attachment of the default framebuffer.
  46193. *
  46194. * @type {GPUTexture?}
  46195. * @default null
  46196. */
  46197. this.colorBuffer = null;
  46198. /**
  46199. * A reference to the default render pass descriptor.
  46200. *
  46201. * @type {Object?}
  46202. * @default null
  46203. */
  46204. this.defaultRenderPassdescriptor = null;
  46205. /**
  46206. * A reference to a backend module holding common utility functions.
  46207. *
  46208. * @type {WebGPUUtils}
  46209. */
  46210. this.utils = new WebGPUUtils( this );
  46211. /**
  46212. * A reference to a backend module holding shader attribute-related
  46213. * utility functions.
  46214. *
  46215. * @type {WebGPUAttributeUtils}
  46216. */
  46217. this.attributeUtils = new WebGPUAttributeUtils( this );
  46218. /**
  46219. * A reference to a backend module holding shader binding-related
  46220. * utility functions.
  46221. *
  46222. * @type {WebGPUBindingUtils}
  46223. */
  46224. this.bindingUtils = new WebGPUBindingUtils( this );
  46225. /**
  46226. * A reference to a backend module holding shader pipeline-related
  46227. * utility functions.
  46228. *
  46229. * @type {WebGPUPipelineUtils}
  46230. */
  46231. this.pipelineUtils = new WebGPUPipelineUtils( this );
  46232. /**
  46233. * A reference to a backend module holding shader texture-related
  46234. * utility functions.
  46235. *
  46236. * @type {WebGPUTextureUtils}
  46237. */
  46238. this.textureUtils = new WebGPUTextureUtils( this );
  46239. /**
  46240. * A map that manages the resolve buffers for occlusion queries.
  46241. *
  46242. * @type {Map<Number,GPUBuffer>}
  46243. */
  46244. this.occludedResolveCache = new Map();
  46245. }
  46246. /**
  46247. * Initializes the backend so it is ready for usage.
  46248. *
  46249. * @async
  46250. * @param {Renderer} renderer - The renderer.
  46251. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46252. */
  46253. async init( renderer ) {
  46254. await super.init( renderer );
  46255. //
  46256. const parameters = this.parameters;
  46257. // create the device if it is not passed with parameters
  46258. let device;
  46259. if ( parameters.device === undefined ) {
  46260. const adapterOptions = {
  46261. powerPreference: parameters.powerPreference
  46262. };
  46263. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  46264. if ( adapter === null ) {
  46265. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  46266. }
  46267. // feature support
  46268. const features = Object.values( GPUFeatureName );
  46269. const supportedFeatures = [];
  46270. for ( const name of features ) {
  46271. if ( adapter.features.has( name ) ) {
  46272. supportedFeatures.push( name );
  46273. }
  46274. }
  46275. const deviceDescriptor = {
  46276. requiredFeatures: supportedFeatures,
  46277. requiredLimits: parameters.requiredLimits
  46278. };
  46279. device = await adapter.requestDevice( deviceDescriptor );
  46280. } else {
  46281. device = parameters.device;
  46282. }
  46283. device.lost.then( ( info ) => {
  46284. const deviceLossInfo = {
  46285. api: 'WebGPU',
  46286. message: info.message || 'Unknown reason',
  46287. reason: info.reason || null,
  46288. originalEvent: info
  46289. };
  46290. renderer.onDeviceLost( deviceLossInfo );
  46291. } );
  46292. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  46293. this.device = device;
  46294. this.context = context;
  46295. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  46296. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  46297. this.context.configure( {
  46298. device: this.device,
  46299. format: this.utils.getPreferredCanvasFormat(),
  46300. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  46301. alphaMode: alphaMode
  46302. } );
  46303. this.updateSize();
  46304. }
  46305. /**
  46306. * The coordinate system of the backend.
  46307. *
  46308. * @type {Number}
  46309. * @readonly
  46310. */
  46311. get coordinateSystem() {
  46312. return WebGPUCoordinateSystem;
  46313. }
  46314. /**
  46315. * This method performs a readback operation by moving buffer data from
  46316. * a storage buffer attribute from the GPU to the CPU.
  46317. *
  46318. * @async
  46319. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46320. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46321. */
  46322. async getArrayBufferAsync( attribute ) {
  46323. return await this.attributeUtils.getArrayBufferAsync( attribute );
  46324. }
  46325. /**
  46326. * Returns the backend's rendering context.
  46327. *
  46328. * @return {GPUCanvasContext} The rendering context.
  46329. */
  46330. getContext() {
  46331. return this.context;
  46332. }
  46333. /**
  46334. * Returns the default render pass descriptor.
  46335. *
  46336. * In WebGPU, the default framebuffer must be configured
  46337. * like custom framebuffers so the backend needs a render
  46338. * pass descriptor even when rendering directly to screen.
  46339. *
  46340. * @private
  46341. * @return {Object} The render pass descriptor.
  46342. */
  46343. _getDefaultRenderPassDescriptor() {
  46344. let descriptor = this.defaultRenderPassdescriptor;
  46345. if ( descriptor === null ) {
  46346. const renderer = this.renderer;
  46347. descriptor = {
  46348. colorAttachments: [ {
  46349. view: null
  46350. } ],
  46351. };
  46352. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  46353. descriptor.depthStencilAttachment = {
  46354. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  46355. };
  46356. }
  46357. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46358. if ( this.renderer.samples > 0 ) {
  46359. colorAttachment.view = this.colorBuffer.createView();
  46360. } else {
  46361. colorAttachment.resolveTarget = undefined;
  46362. }
  46363. this.defaultRenderPassdescriptor = descriptor;
  46364. }
  46365. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46366. if ( this.renderer.samples > 0 ) {
  46367. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  46368. } else {
  46369. colorAttachment.view = this.context.getCurrentTexture().createView();
  46370. }
  46371. return descriptor;
  46372. }
  46373. /**
  46374. * Returns the render pass descriptor for the given render context.
  46375. *
  46376. * @private
  46377. * @param {RenderContext} renderContext - The render context.
  46378. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  46379. * @return {Object} The render pass descriptor.
  46380. */
  46381. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  46382. const renderTarget = renderContext.renderTarget;
  46383. const renderTargetData = this.get( renderTarget );
  46384. let descriptors = renderTargetData.descriptors;
  46385. if ( descriptors === undefined ||
  46386. renderTargetData.width !== renderTarget.width ||
  46387. renderTargetData.height !== renderTarget.height ||
  46388. renderTargetData.dimensions !== renderTarget.dimensions ||
  46389. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  46390. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  46391. renderTargetData.samples !== renderTarget.samples ||
  46392. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  46393. ) {
  46394. descriptors = {};
  46395. renderTargetData.descriptors = descriptors;
  46396. // dispose
  46397. const onDispose = () => {
  46398. renderTarget.removeEventListener( 'dispose', onDispose );
  46399. this.delete( renderTarget );
  46400. };
  46401. renderTarget.addEventListener( 'dispose', onDispose );
  46402. }
  46403. const cacheKey = renderContext.getCacheKey();
  46404. let descriptor = descriptors[ cacheKey ];
  46405. if ( descriptor === undefined ) {
  46406. const textures = renderContext.textures;
  46407. const colorAttachments = [];
  46408. let sliceIndex;
  46409. for ( let i = 0; i < textures.length; i ++ ) {
  46410. const textureData = this.get( textures[ i ] );
  46411. const viewDescriptor = {
  46412. label: `colorAttachment_${ i }`,
  46413. baseMipLevel: renderContext.activeMipmapLevel,
  46414. mipLevelCount: 1,
  46415. baseArrayLayer: renderContext.activeCubeFace,
  46416. arrayLayerCount: 1,
  46417. dimension: GPUTextureViewDimension.TwoD
  46418. };
  46419. if ( renderTarget.isRenderTarget3D ) {
  46420. sliceIndex = renderContext.activeCubeFace;
  46421. viewDescriptor.baseArrayLayer = 0;
  46422. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  46423. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46424. } else if ( renderTarget.isRenderTargetArray ) {
  46425. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  46426. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46427. }
  46428. const textureView = textureData.texture.createView( viewDescriptor );
  46429. let view, resolveTarget;
  46430. if ( textureData.msaaTexture !== undefined ) {
  46431. view = textureData.msaaTexture.createView();
  46432. resolveTarget = textureView;
  46433. } else {
  46434. view = textureView;
  46435. resolveTarget = undefined;
  46436. }
  46437. colorAttachments.push( {
  46438. view,
  46439. depthSlice: sliceIndex,
  46440. resolveTarget,
  46441. loadOp: GPULoadOp.Load,
  46442. storeOp: GPUStoreOp.Store,
  46443. ...colorAttachmentsConfig
  46444. } );
  46445. }
  46446. descriptor = {
  46447. colorAttachments,
  46448. };
  46449. if ( renderContext.depth ) {
  46450. const depthTextureData = this.get( renderContext.depthTexture );
  46451. const depthStencilAttachment = {
  46452. view: depthTextureData.texture.createView()
  46453. };
  46454. descriptor.depthStencilAttachment = depthStencilAttachment;
  46455. }
  46456. descriptors[ cacheKey ] = descriptor;
  46457. renderTargetData.width = renderTarget.width;
  46458. renderTargetData.height = renderTarget.height;
  46459. renderTargetData.samples = renderTarget.samples;
  46460. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  46461. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  46462. renderTargetData.dimensions = renderTarget.dimensions;
  46463. renderTargetData.depthSlice = sliceIndex;
  46464. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  46465. }
  46466. return descriptor;
  46467. }
  46468. /**
  46469. * This method is executed at the beginning of a render call and prepares
  46470. * the WebGPU state for upcoming render calls
  46471. *
  46472. * @param {RenderContext} renderContext - The render context.
  46473. */
  46474. beginRender( renderContext ) {
  46475. const renderContextData = this.get( renderContext );
  46476. const device = this.device;
  46477. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46478. let occlusionQuerySet;
  46479. if ( occlusionQueryCount > 0 ) {
  46480. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  46481. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  46482. // Get a reference to the array of objects with queries. The renderContextData property
  46483. // can be changed by another render pass before the buffer.mapAsyc() completes.
  46484. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  46485. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  46486. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  46487. //
  46488. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  46489. renderContextData.occlusionQuerySet = occlusionQuerySet;
  46490. renderContextData.occlusionQueryIndex = 0;
  46491. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  46492. renderContextData.lastOcclusionObject = null;
  46493. }
  46494. let descriptor;
  46495. if ( renderContext.textures === null ) {
  46496. descriptor = this._getDefaultRenderPassDescriptor();
  46497. } else {
  46498. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  46499. }
  46500. this.initTimestampQuery( renderContext, descriptor );
  46501. descriptor.occlusionQuerySet = occlusionQuerySet;
  46502. const depthStencilAttachment = descriptor.depthStencilAttachment;
  46503. if ( renderContext.textures !== null ) {
  46504. const colorAttachments = descriptor.colorAttachments;
  46505. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  46506. const colorAttachment = colorAttachments[ i ];
  46507. if ( renderContext.clearColor ) {
  46508. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  46509. colorAttachment.loadOp = GPULoadOp.Clear;
  46510. colorAttachment.storeOp = GPUStoreOp.Store;
  46511. } else {
  46512. colorAttachment.loadOp = GPULoadOp.Load;
  46513. colorAttachment.storeOp = GPUStoreOp.Store;
  46514. }
  46515. }
  46516. } else {
  46517. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46518. if ( renderContext.clearColor ) {
  46519. colorAttachment.clearValue = renderContext.clearColorValue;
  46520. colorAttachment.loadOp = GPULoadOp.Clear;
  46521. colorAttachment.storeOp = GPUStoreOp.Store;
  46522. } else {
  46523. colorAttachment.loadOp = GPULoadOp.Load;
  46524. colorAttachment.storeOp = GPUStoreOp.Store;
  46525. }
  46526. }
  46527. //
  46528. if ( renderContext.depth ) {
  46529. if ( renderContext.clearDepth ) {
  46530. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  46531. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46532. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46533. } else {
  46534. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46535. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46536. }
  46537. }
  46538. if ( renderContext.stencil ) {
  46539. if ( renderContext.clearStencil ) {
  46540. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  46541. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46542. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46543. } else {
  46544. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46545. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46546. }
  46547. }
  46548. //
  46549. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  46550. const currentPass = encoder.beginRenderPass( descriptor );
  46551. //
  46552. renderContextData.descriptor = descriptor;
  46553. renderContextData.encoder = encoder;
  46554. renderContextData.currentPass = currentPass;
  46555. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46556. renderContextData.renderBundles = [];
  46557. //
  46558. if ( renderContext.viewport ) {
  46559. this.updateViewport( renderContext );
  46560. }
  46561. if ( renderContext.scissor ) {
  46562. const { x, y, width, height } = renderContext.scissorValue;
  46563. currentPass.setScissorRect( x, y, width, height );
  46564. }
  46565. }
  46566. /**
  46567. * This method is executed at the end of a render call and finalizes work
  46568. * after draw calls.
  46569. *
  46570. * @param {RenderContext} renderContext - The render context.
  46571. */
  46572. finishRender( renderContext ) {
  46573. const renderContextData = this.get( renderContext );
  46574. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46575. if ( renderContextData.renderBundles.length > 0 ) {
  46576. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  46577. }
  46578. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  46579. renderContextData.currentPass.endOcclusionQuery();
  46580. }
  46581. renderContextData.currentPass.end();
  46582. if ( occlusionQueryCount > 0 ) {
  46583. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  46584. //
  46585. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  46586. if ( queryResolveBuffer === undefined ) {
  46587. queryResolveBuffer = this.device.createBuffer(
  46588. {
  46589. size: bufferSize,
  46590. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  46591. }
  46592. );
  46593. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  46594. }
  46595. //
  46596. const readBuffer = this.device.createBuffer(
  46597. {
  46598. size: bufferSize,
  46599. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46600. }
  46601. );
  46602. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  46603. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  46604. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  46605. renderContextData.occlusionQueryBuffer = readBuffer;
  46606. //
  46607. this.resolveOccludedAsync( renderContext );
  46608. }
  46609. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  46610. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  46611. //
  46612. if ( renderContext.textures !== null ) {
  46613. const textures = renderContext.textures;
  46614. for ( let i = 0; i < textures.length; i ++ ) {
  46615. const texture = textures[ i ];
  46616. if ( texture.generateMipmaps === true ) {
  46617. this.textureUtils.generateMipmaps( texture );
  46618. }
  46619. }
  46620. }
  46621. }
  46622. /**
  46623. * Returns `true` if the given 3D object is fully occluded by other
  46624. * 3D objects in the scene.
  46625. *
  46626. * @param {RenderContext} renderContext - The render context.
  46627. * @param {Object3D} object - The 3D object to test.
  46628. * @return {Boolean} Whether the 3D object is fully occluded or not.
  46629. */
  46630. isOccluded( renderContext, object ) {
  46631. const renderContextData = this.get( renderContext );
  46632. return renderContextData.occluded && renderContextData.occluded.has( object );
  46633. }
  46634. /**
  46635. * This method processes the result of occlusion queries and writes it
  46636. * into render context data.
  46637. *
  46638. * @async
  46639. * @param {RenderContext} renderContext - The render context.
  46640. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  46641. */
  46642. async resolveOccludedAsync( renderContext ) {
  46643. const renderContextData = this.get( renderContext );
  46644. // handle occlusion query results
  46645. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  46646. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  46647. const occluded = new WeakSet();
  46648. renderContextData.currentOcclusionQueryObjects = null;
  46649. renderContextData.currentOcclusionQueryBuffer = null;
  46650. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  46651. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  46652. const results = new BigUint64Array( buffer );
  46653. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  46654. if ( results[ i ] === BigInt( 0 ) ) {
  46655. occluded.add( currentOcclusionQueryObjects[ i ] );
  46656. }
  46657. }
  46658. currentOcclusionQueryBuffer.destroy();
  46659. renderContextData.occluded = occluded;
  46660. }
  46661. }
  46662. /**
  46663. * Updates the viewport with the values from the given render context.
  46664. *
  46665. * @param {RenderContext} renderContext - The render context.
  46666. */
  46667. updateViewport( renderContext ) {
  46668. const { currentPass } = this.get( renderContext );
  46669. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  46670. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  46671. }
  46672. /**
  46673. * Performs a clear operation.
  46674. *
  46675. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  46676. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  46677. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  46678. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  46679. */
  46680. clear( color, depth, stencil, renderTargetContext = null ) {
  46681. const device = this.device;
  46682. const renderer = this.renderer;
  46683. let colorAttachments = [];
  46684. let depthStencilAttachment;
  46685. let clearValue;
  46686. let supportsDepth;
  46687. let supportsStencil;
  46688. if ( color ) {
  46689. const clearColor = this.getClearColor();
  46690. if ( this.renderer.alpha === true ) {
  46691. // premultiply alpha
  46692. const a = clearColor.a;
  46693. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  46694. } else {
  46695. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  46696. }
  46697. }
  46698. if ( renderTargetContext === null ) {
  46699. supportsDepth = renderer.depth;
  46700. supportsStencil = renderer.stencil;
  46701. const descriptor = this._getDefaultRenderPassDescriptor();
  46702. if ( color ) {
  46703. colorAttachments = descriptor.colorAttachments;
  46704. const colorAttachment = colorAttachments[ 0 ];
  46705. colorAttachment.clearValue = clearValue;
  46706. colorAttachment.loadOp = GPULoadOp.Clear;
  46707. colorAttachment.storeOp = GPUStoreOp.Store;
  46708. }
  46709. if ( supportsDepth || supportsStencil ) {
  46710. depthStencilAttachment = descriptor.depthStencilAttachment;
  46711. }
  46712. } else {
  46713. supportsDepth = renderTargetContext.depth;
  46714. supportsStencil = renderTargetContext.stencil;
  46715. if ( color ) {
  46716. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  46717. colorAttachments = descriptor.colorAttachments;
  46718. }
  46719. if ( supportsDepth || supportsStencil ) {
  46720. const depthTextureData = this.get( renderTargetContext.depthTexture );
  46721. depthStencilAttachment = {
  46722. view: depthTextureData.texture.createView()
  46723. };
  46724. }
  46725. }
  46726. //
  46727. if ( supportsDepth ) {
  46728. if ( depth ) {
  46729. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46730. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  46731. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46732. } else {
  46733. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46734. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46735. }
  46736. }
  46737. //
  46738. if ( supportsStencil ) {
  46739. if ( stencil ) {
  46740. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46741. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  46742. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46743. } else {
  46744. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46745. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46746. }
  46747. }
  46748. //
  46749. const encoder = device.createCommandEncoder( { label: 'clear' } );
  46750. const currentPass = encoder.beginRenderPass( {
  46751. colorAttachments,
  46752. depthStencilAttachment
  46753. } );
  46754. currentPass.end();
  46755. device.queue.submit( [ encoder.finish() ] );
  46756. }
  46757. // compute
  46758. /**
  46759. * This method is executed at the beginning of a compute call and
  46760. * prepares the state for upcoming compute tasks.
  46761. *
  46762. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46763. */
  46764. beginCompute( computeGroup ) {
  46765. const groupGPU = this.get( computeGroup );
  46766. const descriptor = {
  46767. label: 'computeGroup_' + computeGroup.id
  46768. };
  46769. this.initTimestampQuery( computeGroup, descriptor );
  46770. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  46771. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  46772. }
  46773. /**
  46774. * Executes a compute command for the given compute node.
  46775. *
  46776. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46777. * @param {Node} computeNode - The compute node.
  46778. * @param {Array<BindGroup>} bindings - The bindings.
  46779. * @param {ComputePipeline} pipeline - The compute pipeline.
  46780. */
  46781. compute( computeGroup, computeNode, bindings, pipeline ) {
  46782. const { passEncoderGPU } = this.get( computeGroup );
  46783. // pipeline
  46784. const pipelineGPU = this.get( pipeline ).pipeline;
  46785. passEncoderGPU.setPipeline( pipelineGPU );
  46786. // bind groups
  46787. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46788. const bindGroup = bindings[ i ];
  46789. const bindingsData = this.get( bindGroup );
  46790. passEncoderGPU.setBindGroup( i, bindingsData.group );
  46791. }
  46792. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  46793. const computeNodeData = this.get( computeNode );
  46794. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  46795. const { dispatchSize } = computeNodeData;
  46796. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  46797. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  46798. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  46799. } else {
  46800. dispatchSize.x = computeNode.dispatchCount;
  46801. }
  46802. passEncoderGPU.dispatchWorkgroups(
  46803. dispatchSize.x,
  46804. dispatchSize.y,
  46805. dispatchSize.z
  46806. );
  46807. }
  46808. /**
  46809. * This method is executed at the end of a compute call and
  46810. * finalizes work after compute tasks.
  46811. *
  46812. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46813. */
  46814. finishCompute( computeGroup ) {
  46815. const groupData = this.get( computeGroup );
  46816. groupData.passEncoderGPU.end();
  46817. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  46818. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  46819. }
  46820. /**
  46821. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  46822. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  46823. *
  46824. * @async
  46825. * @return {Promise} A Promise that resolves when synchronization has been finished.
  46826. */
  46827. async waitForGPU() {
  46828. await this.device.queue.onSubmittedWorkDone();
  46829. }
  46830. // render object
  46831. /**
  46832. * Executes a draw command for the given render object.
  46833. *
  46834. * @param {RenderObject} renderObject - The render object to draw.
  46835. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46836. */
  46837. draw( renderObject, info ) {
  46838. const { object, context, pipeline } = renderObject;
  46839. const bindings = renderObject.getBindings();
  46840. const renderContextData = this.get( context );
  46841. const pipelineGPU = this.get( pipeline ).pipeline;
  46842. const currentSets = renderContextData.currentSets;
  46843. const passEncoderGPU = renderContextData.currentPass;
  46844. const drawParams = renderObject.getDrawParameters();
  46845. if ( drawParams === null ) return;
  46846. // pipeline
  46847. if ( currentSets.pipeline !== pipelineGPU ) {
  46848. passEncoderGPU.setPipeline( pipelineGPU );
  46849. currentSets.pipeline = pipelineGPU;
  46850. }
  46851. // bind groups
  46852. const currentBindingGroups = currentSets.bindingGroups;
  46853. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46854. const bindGroup = bindings[ i ];
  46855. const bindingsData = this.get( bindGroup );
  46856. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  46857. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  46858. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  46859. }
  46860. }
  46861. // attributes
  46862. const index = renderObject.getIndex();
  46863. const hasIndex = ( index !== null );
  46864. // index
  46865. if ( hasIndex === true ) {
  46866. if ( currentSets.index !== index ) {
  46867. const buffer = this.get( index ).buffer;
  46868. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46869. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  46870. currentSets.index = index;
  46871. }
  46872. }
  46873. // vertex buffers
  46874. const vertexBuffers = renderObject.getVertexBuffers();
  46875. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  46876. const vertexBuffer = vertexBuffers[ i ];
  46877. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  46878. const buffer = this.get( vertexBuffer ).buffer;
  46879. passEncoderGPU.setVertexBuffer( i, buffer );
  46880. currentSets.attributes[ i ] = vertexBuffer;
  46881. }
  46882. }
  46883. // occlusion queries - handle multiple consecutive draw calls for an object
  46884. if ( renderContextData.occlusionQuerySet !== undefined ) {
  46885. const lastObject = renderContextData.lastOcclusionObject;
  46886. if ( lastObject !== object ) {
  46887. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46888. passEncoderGPU.endOcclusionQuery();
  46889. renderContextData.occlusionQueryIndex ++;
  46890. }
  46891. if ( object.occlusionTest === true ) {
  46892. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  46893. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  46894. }
  46895. renderContextData.lastOcclusionObject = object;
  46896. }
  46897. }
  46898. // draw
  46899. const draw = () => {
  46900. if ( object.isBatchedMesh === true ) {
  46901. const starts = object._multiDrawStarts;
  46902. const counts = object._multiDrawCounts;
  46903. const drawCount = object._multiDrawCount;
  46904. const drawInstances = object._multiDrawInstances;
  46905. for ( let i = 0; i < drawCount; i ++ ) {
  46906. const count = drawInstances ? drawInstances[ i ] : 1;
  46907. const firstInstance = count > 1 ? 0 : i;
  46908. if ( hasIndex === true ) {
  46909. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  46910. } else {
  46911. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  46912. }
  46913. }
  46914. } else if ( hasIndex === true ) {
  46915. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  46916. const indirect = renderObject.getIndirect();
  46917. if ( indirect !== null ) {
  46918. const buffer = this.get( indirect ).buffer;
  46919. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  46920. } else {
  46921. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  46922. }
  46923. info.update( object, indexCount, instanceCount );
  46924. } else {
  46925. const { vertexCount, instanceCount, firstVertex } = drawParams;
  46926. const indirect = renderObject.getIndirect();
  46927. if ( indirect !== null ) {
  46928. const buffer = this.get( indirect ).buffer;
  46929. passEncoderGPU.drawIndirect( buffer, 0 );
  46930. } else {
  46931. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  46932. }
  46933. info.update( object, vertexCount, instanceCount );
  46934. }
  46935. };
  46936. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  46937. const cameraData = this.get( renderObject.camera );
  46938. const cameras = renderObject.camera.cameras;
  46939. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  46940. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  46941. const bindingsData = this.get( cameraIndex );
  46942. const indexesGPU = [];
  46943. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  46944. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46945. data[ 0 ] = i;
  46946. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  46947. indexesGPU.push( bindGroupIndex );
  46948. }
  46949. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  46950. }
  46951. const pixelRatio = this.renderer.getPixelRatio();
  46952. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46953. const subCamera = cameras[ i ];
  46954. if ( object.layers.test( subCamera.layers ) ) {
  46955. const vp = subCamera.viewport;
  46956. passEncoderGPU.setViewport(
  46957. Math.floor( vp.x * pixelRatio ),
  46958. Math.floor( vp.y * pixelRatio ),
  46959. Math.floor( vp.width * pixelRatio ),
  46960. Math.floor( vp.height * pixelRatio ),
  46961. context.viewportValue.minDepth,
  46962. context.viewportValue.maxDepth
  46963. );
  46964. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  46965. draw();
  46966. }
  46967. }
  46968. } else {
  46969. draw();
  46970. }
  46971. }
  46972. // cache key
  46973. /**
  46974. * Returns `true` if the render pipeline requires an update.
  46975. *
  46976. * @param {RenderObject} renderObject - The render object.
  46977. * @return {Boolean} Whether the render pipeline requires an update or not.
  46978. */
  46979. needsRenderUpdate( renderObject ) {
  46980. const data = this.get( renderObject );
  46981. const { object, material } = renderObject;
  46982. const utils = this.utils;
  46983. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  46984. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  46985. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46986. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46987. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  46988. let needsUpdate = false;
  46989. if ( data.material !== material || data.materialVersion !== material.version ||
  46990. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  46991. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  46992. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  46993. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  46994. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  46995. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  46996. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  46997. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  46998. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  46999. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  47000. data.primitiveTopology !== primitiveTopology ||
  47001. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  47002. ) {
  47003. data.material = material; data.materialVersion = material.version;
  47004. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  47005. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  47006. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  47007. data.colorWrite = material.colorWrite;
  47008. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  47009. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  47010. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  47011. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  47012. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  47013. data.sampleCount = sampleCount;
  47014. data.colorSpace = colorSpace;
  47015. data.colorFormat = colorFormat;
  47016. data.depthStencilFormat = depthStencilFormat;
  47017. data.primitiveTopology = primitiveTopology;
  47018. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  47019. needsUpdate = true;
  47020. }
  47021. return needsUpdate;
  47022. }
  47023. /**
  47024. * Returns a cache key that is used to identify render pipelines.
  47025. *
  47026. * @param {RenderObject} renderObject - The render object.
  47027. * @return {String} The cache key.
  47028. */
  47029. getRenderCacheKey( renderObject ) {
  47030. const { object, material } = renderObject;
  47031. const utils = this.utils;
  47032. const renderContext = renderObject.context;
  47033. return [
  47034. material.transparent, material.blending, material.premultipliedAlpha,
  47035. material.blendSrc, material.blendDst, material.blendEquation,
  47036. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  47037. material.colorWrite,
  47038. material.depthWrite, material.depthTest, material.depthFunc,
  47039. material.stencilWrite, material.stencilFunc,
  47040. material.stencilFail, material.stencilZFail, material.stencilZPass,
  47041. material.stencilFuncMask, material.stencilWriteMask,
  47042. material.side,
  47043. utils.getSampleCountRenderContext( renderContext ),
  47044. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  47045. utils.getPrimitiveTopology( object, material ),
  47046. renderObject.getGeometryCacheKey(),
  47047. renderObject.clippingContextCacheKey
  47048. ].join();
  47049. }
  47050. // textures
  47051. /**
  47052. * Creates a GPU sampler for the given texture.
  47053. *
  47054. * @param {Texture} texture - The texture to create the sampler for.
  47055. */
  47056. createSampler( texture ) {
  47057. this.textureUtils.createSampler( texture );
  47058. }
  47059. /**
  47060. * Destroys the GPU sampler for the given texture.
  47061. *
  47062. * @param {Texture} texture - The texture to destroy the sampler for.
  47063. */
  47064. destroySampler( texture ) {
  47065. this.textureUtils.destroySampler( texture );
  47066. }
  47067. /**
  47068. * Creates a default texture for the given texture that can be used
  47069. * as a placeholder until the actual texture is ready for usage.
  47070. *
  47071. * @param {Texture} texture - The texture to create a default texture for.
  47072. */
  47073. createDefaultTexture( texture ) {
  47074. this.textureUtils.createDefaultTexture( texture );
  47075. }
  47076. /**
  47077. * Defines a texture on the GPU for the given texture object.
  47078. *
  47079. * @param {Texture} texture - The texture.
  47080. * @param {Object} [options={}] - Optional configuration parameter.
  47081. */
  47082. createTexture( texture, options ) {
  47083. this.textureUtils.createTexture( texture, options );
  47084. }
  47085. /**
  47086. * Uploads the updated texture data to the GPU.
  47087. *
  47088. * @param {Texture} texture - The texture.
  47089. * @param {Object} [options={}] - Optional configuration parameter.
  47090. */
  47091. updateTexture( texture, options ) {
  47092. this.textureUtils.updateTexture( texture, options );
  47093. }
  47094. /**
  47095. * Generates mipmaps for the given texture.
  47096. *
  47097. * @param {Texture} texture - The texture.
  47098. */
  47099. generateMipmaps( texture ) {
  47100. this.textureUtils.generateMipmaps( texture );
  47101. }
  47102. /**
  47103. * Destroys the GPU data for the given texture object.
  47104. *
  47105. * @param {Texture} texture - The texture.
  47106. */
  47107. destroyTexture( texture ) {
  47108. this.textureUtils.destroyTexture( texture );
  47109. }
  47110. /**
  47111. * Returns texture data as a typed array.
  47112. *
  47113. * @async
  47114. * @param {Texture} texture - The texture to copy.
  47115. * @param {Number} x - The x coordinate of the copy origin.
  47116. * @param {Number} y - The y coordinate of the copy origin.
  47117. * @param {Number} width - The width of the copy.
  47118. * @param {Number} height - The height of the copy.
  47119. * @param {Number} faceIndex - The face index.
  47120. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47121. */
  47122. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47123. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47124. }
  47125. /**
  47126. * Inits a time stamp query for the given render context.
  47127. *
  47128. * @param {RenderContext} renderContext - The render context.
  47129. * @param {Object} descriptor - The query descriptor.
  47130. */
  47131. initTimestampQuery( renderContext, descriptor ) {
  47132. if ( ! this.trackTimestamp ) return;
  47133. const renderContextData = this.get( renderContext );
  47134. // init query set if not exists
  47135. if ( ! renderContextData.timestampQuerySet ) {
  47136. const type = renderContext.isComputeNode ? 'compute' : 'render';
  47137. renderContextData.timestampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  47138. }
  47139. // augment descriptor
  47140. descriptor.timestampWrites = {
  47141. querySet: renderContextData.timestampQuerySet,
  47142. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  47143. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  47144. };
  47145. }
  47146. /**
  47147. * Prepares the timestamp buffer.
  47148. *
  47149. * @param {RenderContext} renderContext - The render context.
  47150. * @param {GPUCommandEncoder} encoder - The command encoder.
  47151. */
  47152. prepareTimestampBuffer( renderContext, encoder ) {
  47153. if ( ! this.trackTimestamp ) return;
  47154. const renderContextData = this.get( renderContext );
  47155. const size = 2 * BigUint64Array.BYTES_PER_ELEMENT;
  47156. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  47157. renderContextData.currentTimestampQueryBuffers = {
  47158. resolveBuffer: this.device.createBuffer( {
  47159. label: 'timestamp resolve buffer',
  47160. size: size,
  47161. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  47162. } ),
  47163. resultBuffer: this.device.createBuffer( {
  47164. label: 'timestamp result buffer',
  47165. size: size,
  47166. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  47167. } )
  47168. };
  47169. }
  47170. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47171. encoder.resolveQuerySet( renderContextData.timestampQuerySet, 0, 2, resolveBuffer, 0 );
  47172. if ( resultBuffer.mapState === 'unmapped' ) {
  47173. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  47174. }
  47175. }
  47176. /**
  47177. * Resolves the time stamp for the given render context and type.
  47178. *
  47179. * @async
  47180. * @param {RenderContext} renderContext - The render context.
  47181. * @param {String} type - The render context.
  47182. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  47183. */
  47184. async resolveTimestampAsync( renderContext, type = 'render' ) {
  47185. if ( ! this.trackTimestamp ) return;
  47186. const renderContextData = this.get( renderContext );
  47187. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  47188. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47189. if ( resultBuffer.mapState === 'unmapped' ) {
  47190. await resultBuffer.mapAsync( GPUMapMode.READ );
  47191. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  47192. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  47193. this.renderer.info.updateTimestamp( type, duration );
  47194. resultBuffer.unmap();
  47195. }
  47196. }
  47197. // node builder
  47198. /**
  47199. * Returns a node builder for the given render object.
  47200. *
  47201. * @param {RenderObject} object - The render object.
  47202. * @param {Renderer} renderer - The renderer.
  47203. * @return {WGSLNodeBuilder} The node builder.
  47204. */
  47205. createNodeBuilder( object, renderer ) {
  47206. return new WGSLNodeBuilder( object, renderer );
  47207. }
  47208. // program
  47209. /**
  47210. * Creates a shader program from the given programmable stage.
  47211. *
  47212. * @param {ProgrammableStage} program - The programmable stage.
  47213. */
  47214. createProgram( program ) {
  47215. const programGPU = this.get( program );
  47216. programGPU.module = {
  47217. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  47218. entryPoint: 'main'
  47219. };
  47220. }
  47221. /**
  47222. * Destroys the shader program of the given programmable stage.
  47223. *
  47224. * @param {ProgrammableStage} program - The programmable stage.
  47225. */
  47226. destroyProgram( program ) {
  47227. this.delete( program );
  47228. }
  47229. // pipelines
  47230. /**
  47231. * Creates a render pipeline for the given render object.
  47232. *
  47233. * @param {RenderObject} renderObject - The render object.
  47234. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47235. */
  47236. createRenderPipeline( renderObject, promises ) {
  47237. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  47238. }
  47239. /**
  47240. * Creates a compute pipeline for the given compute node.
  47241. *
  47242. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47243. * @param {Array<BindGroup>} bindings - The bindings.
  47244. */
  47245. createComputePipeline( computePipeline, bindings ) {
  47246. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  47247. }
  47248. /**
  47249. * Prepares the state for encoding render bundles.
  47250. *
  47251. * @param {RenderContext} renderContext - The render context.
  47252. */
  47253. beginBundle( renderContext ) {
  47254. const renderContextData = this.get( renderContext );
  47255. renderContextData._currentPass = renderContextData.currentPass;
  47256. renderContextData._currentSets = renderContextData.currentSets;
  47257. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47258. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  47259. }
  47260. /**
  47261. * After processing render bundles this method finalizes related work.
  47262. *
  47263. * @param {RenderContext} renderContext - The render context.
  47264. * @param {RenderBundle} bundle - The render bundle.
  47265. */
  47266. finishBundle( renderContext, bundle ) {
  47267. const renderContextData = this.get( renderContext );
  47268. const bundleEncoder = renderContextData.currentPass;
  47269. const bundleGPU = bundleEncoder.finish();
  47270. this.get( bundle ).bundleGPU = bundleGPU;
  47271. // restore render pass state
  47272. renderContextData.currentSets = renderContextData._currentSets;
  47273. renderContextData.currentPass = renderContextData._currentPass;
  47274. }
  47275. /**
  47276. * Adds a render bundle to the render context data.
  47277. *
  47278. * @param {RenderContext} renderContext - The render context.
  47279. * @param {RenderBundle} bundle - The render bundle to add.
  47280. */
  47281. addBundle( renderContext, bundle ) {
  47282. const renderContextData = this.get( renderContext );
  47283. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  47284. }
  47285. // bindings
  47286. /**
  47287. * Creates bindings from the given bind group definition.
  47288. *
  47289. * @param {BindGroup} bindGroup - The bind group.
  47290. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47291. * @param {Number} cacheIndex - The cache index.
  47292. * @param {Number} version - The version.
  47293. */
  47294. createBindings( bindGroup, bindings, cacheIndex, version ) {
  47295. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47296. }
  47297. /**
  47298. * Updates the given bind group definition.
  47299. *
  47300. * @param {BindGroup} bindGroup - The bind group.
  47301. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47302. * @param {Number} cacheIndex - The cache index.
  47303. * @param {Number} version - The version.
  47304. */
  47305. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  47306. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47307. }
  47308. /**
  47309. * Updates a buffer binding.
  47310. *
  47311. * @param {Buffer} binding - The buffer binding to update.
  47312. */
  47313. updateBinding( binding ) {
  47314. this.bindingUtils.updateBinding( binding );
  47315. }
  47316. // attributes
  47317. /**
  47318. * Creates the buffer of an indexed shader attribute.
  47319. *
  47320. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47321. */
  47322. createIndexAttribute( attribute ) {
  47323. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47324. }
  47325. /**
  47326. * Creates the GPU buffer of a shader attribute.
  47327. *
  47328. * @param {BufferAttribute} attribute - The buffer attribute.
  47329. */
  47330. createAttribute( attribute ) {
  47331. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47332. }
  47333. /**
  47334. * Creates the GPU buffer of a storage attribute.
  47335. *
  47336. * @param {BufferAttribute} attribute - The buffer attribute.
  47337. */
  47338. createStorageAttribute( attribute ) {
  47339. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47340. }
  47341. /**
  47342. * Creates the GPU buffer of an indirect storage attribute.
  47343. *
  47344. * @param {BufferAttribute} attribute - The buffer attribute.
  47345. */
  47346. createIndirectStorageAttribute( attribute ) {
  47347. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47348. }
  47349. /**
  47350. * Updates the GPU buffer of a shader attribute.
  47351. *
  47352. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47353. */
  47354. updateAttribute( attribute ) {
  47355. this.attributeUtils.updateAttribute( attribute );
  47356. }
  47357. /**
  47358. * Destroys the GPU buffer of a shader attribute.
  47359. *
  47360. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47361. */
  47362. destroyAttribute( attribute ) {
  47363. this.attributeUtils.destroyAttribute( attribute );
  47364. }
  47365. // canvas
  47366. /**
  47367. * Triggers an update of the default render pass descriptor.
  47368. */
  47369. updateSize() {
  47370. this.colorBuffer = this.textureUtils.getColorBuffer();
  47371. this.defaultRenderPassdescriptor = null;
  47372. }
  47373. // utils public
  47374. /**
  47375. * Returns the maximum anisotropy texture filtering value.
  47376. *
  47377. * @return {Number} The maximum anisotropy texture filtering value.
  47378. */
  47379. getMaxAnisotropy() {
  47380. return 16;
  47381. }
  47382. /**
  47383. * Checks if the given feature is supported by the backend.
  47384. *
  47385. * @param {String} name - The feature's name.
  47386. * @return {Boolean} Whether the feature is supported or not.
  47387. */
  47388. hasFeature( name ) {
  47389. return this.device.features.has( name );
  47390. }
  47391. /**
  47392. * Copies data of the given source texture to the given destination texture.
  47393. *
  47394. * @param {Texture} srcTexture - The source texture.
  47395. * @param {Texture} dstTexture - The destination texture.
  47396. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  47397. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  47398. * @param {Number} [level=0] - The mip level to copy.
  47399. */
  47400. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  47401. let dstX = 0;
  47402. let dstY = 0;
  47403. let dstLayer = 0;
  47404. let srcX = 0;
  47405. let srcY = 0;
  47406. let srcLayer = 0;
  47407. let srcWidth = srcTexture.image.width;
  47408. let srcHeight = srcTexture.image.height;
  47409. if ( srcRegion !== null ) {
  47410. srcX = srcRegion.x;
  47411. srcY = srcRegion.y;
  47412. srcLayer = srcRegion.z || 0;
  47413. srcWidth = srcRegion.width;
  47414. srcHeight = srcRegion.height;
  47415. }
  47416. if ( dstPosition !== null ) {
  47417. dstX = dstPosition.x;
  47418. dstY = dstPosition.y;
  47419. dstLayer = dstPosition.z || 0;
  47420. }
  47421. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  47422. const sourceGPU = this.get( srcTexture ).texture;
  47423. const destinationGPU = this.get( dstTexture ).texture;
  47424. encoder.copyTextureToTexture(
  47425. {
  47426. texture: sourceGPU,
  47427. mipLevel: level,
  47428. origin: { x: srcX, y: srcY, z: srcLayer }
  47429. },
  47430. {
  47431. texture: destinationGPU,
  47432. mipLevel: level,
  47433. origin: { x: dstX, y: dstY, z: dstLayer }
  47434. },
  47435. [
  47436. srcWidth,
  47437. srcHeight,
  47438. 1
  47439. ]
  47440. );
  47441. this.device.queue.submit( [ encoder.finish() ] );
  47442. }
  47443. /**
  47444. * Copies the current bound framebuffer to the given texture.
  47445. *
  47446. * @param {Texture} texture - The destination texture.
  47447. * @param {RenderContext} renderContext - The render context.
  47448. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47449. */
  47450. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47451. const renderContextData = this.get( renderContext );
  47452. let sourceGPU = null;
  47453. if ( renderContext.renderTarget ) {
  47454. if ( texture.isDepthTexture ) {
  47455. sourceGPU = this.get( renderContext.depthTexture ).texture;
  47456. } else {
  47457. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  47458. }
  47459. } else {
  47460. if ( texture.isDepthTexture ) {
  47461. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  47462. } else {
  47463. sourceGPU = this.context.getCurrentTexture();
  47464. }
  47465. }
  47466. const destinationGPU = this.get( texture ).texture;
  47467. if ( sourceGPU.format !== destinationGPU.format ) {
  47468. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  47469. return;
  47470. }
  47471. let encoder;
  47472. if ( renderContextData.currentPass ) {
  47473. renderContextData.currentPass.end();
  47474. encoder = renderContextData.encoder;
  47475. } else {
  47476. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  47477. }
  47478. encoder.copyTextureToTexture(
  47479. {
  47480. texture: sourceGPU,
  47481. origin: [ rectangle.x, rectangle.y, 0 ],
  47482. },
  47483. {
  47484. texture: destinationGPU
  47485. },
  47486. [
  47487. rectangle.z,
  47488. rectangle.w
  47489. ]
  47490. );
  47491. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  47492. if ( renderContextData.currentPass ) {
  47493. const { descriptor } = renderContextData;
  47494. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  47495. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  47496. }
  47497. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47498. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47499. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  47500. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47501. if ( renderContext.viewport ) {
  47502. this.updateViewport( renderContext );
  47503. }
  47504. if ( renderContext.scissor ) {
  47505. const { x, y, width, height } = renderContext.scissorValue;
  47506. renderContextData.currentPass.setScissorRect( x, y, width, height );
  47507. }
  47508. } else {
  47509. this.device.queue.submit( [ encoder.finish() ] );
  47510. }
  47511. }
  47512. }
  47513. class IESSpotLight extends SpotLight {
  47514. constructor( color, intensity, distance, angle, penumbra, decay ) {
  47515. super( color, intensity, distance, angle, penumbra, decay );
  47516. this.iesMap = null;
  47517. }
  47518. copy( source, recursive ) {
  47519. super.copy( source, recursive );
  47520. this.iesMap = source.iesMap;
  47521. return this;
  47522. }
  47523. }
  47524. /**
  47525. * This version of a node library represents the standard version
  47526. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  47527. * techniques and materials to node-based implementations.
  47528. *
  47529. * @private
  47530. * @augments NodeLibrary
  47531. */
  47532. class StandardNodeLibrary extends NodeLibrary {
  47533. /**
  47534. * Constructs a new standard node library.
  47535. */
  47536. constructor() {
  47537. super();
  47538. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  47539. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  47540. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  47541. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  47542. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  47543. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  47544. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  47545. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  47546. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  47547. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  47548. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  47549. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  47550. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  47551. this.addLight( PointLightNode, PointLight );
  47552. this.addLight( DirectionalLightNode, DirectionalLight );
  47553. this.addLight( RectAreaLightNode, RectAreaLight );
  47554. this.addLight( SpotLightNode, SpotLight );
  47555. this.addLight( AmbientLightNode, AmbientLight );
  47556. this.addLight( HemisphereLightNode, HemisphereLight );
  47557. this.addLight( LightProbeNode, LightProbe );
  47558. this.addLight( IESSpotLightNode, IESSpotLight );
  47559. this.addToneMapping( linearToneMapping, LinearToneMapping );
  47560. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  47561. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  47562. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  47563. this.addToneMapping( agxToneMapping, AgXToneMapping );
  47564. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  47565. }
  47566. }
  47567. /*
  47568. const debugHandler = {
  47569. get: function ( target, name ) {
  47570. // Add |update
  47571. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  47572. return target[ name ];
  47573. }
  47574. };
  47575. */
  47576. /**
  47577. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  47578. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  47579. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  47580. *
  47581. * @augments module:Renderer~Renderer
  47582. */
  47583. class WebGPURenderer extends Renderer {
  47584. /**
  47585. * Constructs a new WebGPU renderer.
  47586. *
  47587. * @param {Object} parameters - The configuration parameter.
  47588. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47589. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47590. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47591. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47592. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47593. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  47594. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47595. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  47596. */
  47597. constructor( parameters = {} ) {
  47598. let BackendClass;
  47599. if ( parameters.forceWebGL ) {
  47600. BackendClass = WebGLBackend;
  47601. } else {
  47602. BackendClass = WebGPUBackend;
  47603. parameters.getFallback = () => {
  47604. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  47605. return new WebGLBackend( parameters );
  47606. };
  47607. }
  47608. const backend = new BackendClass( parameters );
  47609. //super( new Proxy( backend, debugHandler ) );
  47610. super( backend, parameters );
  47611. /**
  47612. * The generic default value is overwritten with the
  47613. * standard node library for type mapping.
  47614. *
  47615. * @type {StandardNodeLibrary}
  47616. */
  47617. this.library = new StandardNodeLibrary();
  47618. /**
  47619. * This flag can be used for type testing.
  47620. *
  47621. * @type {Boolean}
  47622. * @readonly
  47623. * @default true
  47624. */
  47625. this.isWebGPURenderer = true;
  47626. }
  47627. }
  47628. /**
  47629. * A specialized group which enables applications access to the
  47630. * Render Bundle API of WebGPU. The group with all its descendant nodes
  47631. * are considered as one render bundle and processed as such by
  47632. * the renderer.
  47633. *
  47634. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  47635. * With a WebGL backend, the group can technically be rendered but without
  47636. * any performance improvements.
  47637. *
  47638. * @augments Group
  47639. */
  47640. class BundleGroup extends Group {
  47641. /**
  47642. * Constructs a new bundle group.
  47643. */
  47644. constructor() {
  47645. super();
  47646. /**
  47647. * This flag can be used for type testing.
  47648. *
  47649. * @type {Boolean}
  47650. * @readonly
  47651. * @default true
  47652. */
  47653. this.isBundleGroup = true;
  47654. /**
  47655. * This property is only relevant for detecting types
  47656. * during serialization/deserialization. It should always
  47657. * match the class name.
  47658. *
  47659. * @type {String}
  47660. * @readonly
  47661. * @default 'BundleGroup'
  47662. */
  47663. this.type = 'BundleGroup';
  47664. /**
  47665. * Whether the bundle is static or not. When set to `true`, the structure
  47666. * is assumed to be static and does not change. E.g. no new objects are
  47667. * added to the group
  47668. *
  47669. * If a change is required, an update can still be forced by setting the
  47670. * `needsUpdate` flag to `true`.
  47671. *
  47672. * @type {Boolean}
  47673. * @default true
  47674. */
  47675. this.static = true;
  47676. /**
  47677. * The bundle group's version.
  47678. *
  47679. * @type {Number}
  47680. * @readonly
  47681. * @default 0
  47682. */
  47683. this.version = 0;
  47684. }
  47685. /**
  47686. * Set this property to `true` when the bundle group has changed.
  47687. *
  47688. * @type {Boolean}
  47689. * @default false
  47690. * @param {Boolean} value
  47691. */
  47692. set needsUpdate( value ) {
  47693. if ( value === true ) this.version ++;
  47694. }
  47695. }
  47696. /**
  47697. * This module is responsible to manage the post processing setups in apps.
  47698. * You usually create a single instance of this class and use it to define
  47699. * the output of your post processing effect chain.
  47700. * ```js
  47701. * const postProcessing = new PostProcessing( renderer );
  47702. *
  47703. * const scenePass = pass( scene, camera );
  47704. *
  47705. * postProcessing.outputNode = scenePass;
  47706. * ```
  47707. */
  47708. class PostProcessing {
  47709. /**
  47710. * Constructs a new post processing management module.
  47711. *
  47712. * @param {Renderer} renderer - A reference to the renderer.
  47713. * @param {Node<vec4>} outputNode - An optional output node.
  47714. */
  47715. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  47716. /**
  47717. * A reference to the renderer.
  47718. *
  47719. * @type {Renderer}
  47720. */
  47721. this.renderer = renderer;
  47722. /**
  47723. * A node which defines the final output of the post
  47724. * processing. This is usually the last node in a chain
  47725. * of effect nodes.
  47726. *
  47727. * @type {Node<vec4>}
  47728. */
  47729. this.outputNode = outputNode;
  47730. /**
  47731. * Whether the default output tone mapping and color
  47732. * space transformation should be enabled or not.
  47733. *
  47734. * It is enabled by default by it must be disabled when
  47735. * effects must be executed after tone mapping and color
  47736. * space conversion. A typical example is FXAA which
  47737. * requires sRGB input.
  47738. *
  47739. * When set to `false`, the app must control the output
  47740. * transformation with `RenderOutputNode`.
  47741. *
  47742. * ```js
  47743. * const outputPass = renderOutput( scenePass );
  47744. * ```
  47745. *
  47746. * @type {Boolean}
  47747. */
  47748. this.outputColorTransform = true;
  47749. /**
  47750. * Must be set to `true` when the output node changes.
  47751. *
  47752. * @type {Node<vec4>}
  47753. */
  47754. this.needsUpdate = true;
  47755. const material = new NodeMaterial();
  47756. material.name = 'PostProcessing';
  47757. /**
  47758. * The full screen quad that is used to render
  47759. * the effects.
  47760. *
  47761. * @private
  47762. * @type {QuadMesh}
  47763. */
  47764. this._quadMesh = new QuadMesh( material );
  47765. }
  47766. /**
  47767. * When `PostProcessing` is used to apply post processing effects,
  47768. * the application must use this version of `render()` inside
  47769. * its animation loop (not the one from the renderer).
  47770. */
  47771. render() {
  47772. this._update();
  47773. const renderer = this.renderer;
  47774. const toneMapping = renderer.toneMapping;
  47775. const outputColorSpace = renderer.outputColorSpace;
  47776. renderer.toneMapping = NoToneMapping;
  47777. renderer.outputColorSpace = LinearSRGBColorSpace;
  47778. //
  47779. this._quadMesh.render( renderer );
  47780. //
  47781. renderer.toneMapping = toneMapping;
  47782. renderer.outputColorSpace = outputColorSpace;
  47783. }
  47784. /**
  47785. * Frees internal resources.
  47786. */
  47787. dispose() {
  47788. this._quadMesh.material.dispose();
  47789. }
  47790. /**
  47791. * Updates the state of the module.
  47792. *
  47793. * @private
  47794. */
  47795. _update() {
  47796. if ( this.needsUpdate === true ) {
  47797. const renderer = this.renderer;
  47798. const toneMapping = renderer.toneMapping;
  47799. const outputColorSpace = renderer.outputColorSpace;
  47800. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  47801. this._quadMesh.material.needsUpdate = true;
  47802. this.needsUpdate = false;
  47803. }
  47804. }
  47805. /**
  47806. * When `PostProcessing` is used to apply post processing effects,
  47807. * the application must use this version of `renderAsync()` inside
  47808. * its animation loop (not the one from the renderer).
  47809. *
  47810. * @async
  47811. * @return {Promise} A Promise that resolves when the render has been finished.
  47812. */
  47813. async renderAsync() {
  47814. this._update();
  47815. const renderer = this.renderer;
  47816. const toneMapping = renderer.toneMapping;
  47817. const outputColorSpace = renderer.outputColorSpace;
  47818. renderer.toneMapping = NoToneMapping;
  47819. renderer.outputColorSpace = LinearSRGBColorSpace;
  47820. //
  47821. await this._quadMesh.renderAsync( renderer );
  47822. //
  47823. renderer.toneMapping = toneMapping;
  47824. renderer.outputColorSpace = outputColorSpace;
  47825. }
  47826. }
  47827. /**
  47828. * This special type of texture is intended for compute shaders.
  47829. * It can be used to compute the data of a texture with a compute shader.
  47830. *
  47831. * Note: This type of texture can only be used with `WebGPURenderer`
  47832. * and a WebGPU backend.
  47833. *
  47834. * @augments Texture
  47835. */
  47836. class StorageTexture extends Texture {
  47837. /**
  47838. * Constructs a new storage texture.
  47839. *
  47840. * @param {Number} [width=1] - The storage texture's width.
  47841. * @param {Number} [height=1] - The storage texture's height.
  47842. */
  47843. constructor( width = 1, height = 1 ) {
  47844. super();
  47845. /**
  47846. * The image object which just represents the texture's dimension.
  47847. *
  47848. * @type {{width: Number, height: Number}}
  47849. */
  47850. this.image = { width, height };
  47851. /**
  47852. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  47853. *
  47854. * @type {Number}
  47855. */
  47856. this.magFilter = LinearFilter;
  47857. /**
  47858. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  47859. *
  47860. * @type {Number}
  47861. */
  47862. this.minFilter = LinearFilter;
  47863. /**
  47864. * This flag can be used for type testing.
  47865. *
  47866. * @type {Boolean}
  47867. * @readonly
  47868. * @default true
  47869. */
  47870. this.isStorageTexture = true;
  47871. }
  47872. }
  47873. /**
  47874. * This special type of buffer attribute is intended for compute shaders.
  47875. * It can be used to encode draw parameters for indirect draw calls.
  47876. *
  47877. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  47878. * and a WebGPU backend.
  47879. *
  47880. * @augments StorageBufferAttribute
  47881. */
  47882. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  47883. /**
  47884. * Constructs a new storage buffer attribute.
  47885. *
  47886. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  47887. * The subsequent parameter is then obsolete.
  47888. * @param {Number} itemSize - The item size.
  47889. */
  47890. constructor( count, itemSize ) {
  47891. super( count, itemSize, Uint32Array );
  47892. /**
  47893. * This flag can be used for type testing.
  47894. *
  47895. * @type {Boolean}
  47896. * @readonly
  47897. * @default true
  47898. */
  47899. this.isIndirectStorageBufferAttribute = true;
  47900. }
  47901. }
  47902. /**
  47903. * A loader for loading node objects in the three.js JSON Object/Scene format.
  47904. *
  47905. * @augments Loader
  47906. */
  47907. class NodeLoader extends Loader {
  47908. /**
  47909. * Constructs a new node loader.
  47910. *
  47911. * @param {LoadingManager?} manager - A reference to a loading manager.
  47912. */
  47913. constructor( manager ) {
  47914. super( manager );
  47915. /**
  47916. * Represents a dictionary of textures.
  47917. *
  47918. * @type {Object<String,Texture>}
  47919. */
  47920. this.textures = {};
  47921. /**
  47922. * Represents a dictionary of node types.
  47923. *
  47924. * @type {Object<String,Node.constructor>}
  47925. */
  47926. this.nodes = {};
  47927. }
  47928. /**
  47929. * Loads the node definitions from the given URL.
  47930. *
  47931. * @param {String} url - The path/URL of the file to be loaded.
  47932. * @param {Function} onLoad - Will be called when load completes.
  47933. * @param {Function} onProgress - Will be called while load progresses.
  47934. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  47935. */
  47936. load( url, onLoad, onProgress, onError ) {
  47937. const loader = new FileLoader( this.manager );
  47938. loader.setPath( this.path );
  47939. loader.setRequestHeader( this.requestHeader );
  47940. loader.setWithCredentials( this.withCredentials );
  47941. loader.load( url, ( text ) => {
  47942. try {
  47943. onLoad( this.parse( JSON.parse( text ) ) );
  47944. } catch ( e ) {
  47945. if ( onError ) {
  47946. onError( e );
  47947. } else {
  47948. console.error( e );
  47949. }
  47950. this.manager.itemError( url );
  47951. }
  47952. }, onProgress, onError );
  47953. }
  47954. /**
  47955. * Parse the node dependencies for the loaded node.
  47956. *
  47957. * @param {Object} json - The JSON definition
  47958. * @return {Object<String,Node>} A dictionary with node dependencies.
  47959. */
  47960. parseNodes( json ) {
  47961. const nodes = {};
  47962. if ( json !== undefined ) {
  47963. for ( const nodeJSON of json ) {
  47964. const { uuid, type } = nodeJSON;
  47965. nodes[ uuid ] = this.createNodeFromType( type );
  47966. nodes[ uuid ].uuid = uuid;
  47967. }
  47968. const meta = { nodes, textures: this.textures };
  47969. for ( const nodeJSON of json ) {
  47970. nodeJSON.meta = meta;
  47971. const node = nodes[ nodeJSON.uuid ];
  47972. node.deserialize( nodeJSON );
  47973. delete nodeJSON.meta;
  47974. }
  47975. }
  47976. return nodes;
  47977. }
  47978. /**
  47979. * Parses the node from the given JSON.
  47980. *
  47981. * @param {Object} json - The JSON definition
  47982. * @return {Node} The parsed node.
  47983. */
  47984. parse( json ) {
  47985. const node = this.createNodeFromType( json.type );
  47986. node.uuid = json.uuid;
  47987. const nodes = this.parseNodes( json.nodes );
  47988. const meta = { nodes, textures: this.textures };
  47989. json.meta = meta;
  47990. node.deserialize( json );
  47991. delete json.meta;
  47992. return node;
  47993. }
  47994. /**
  47995. * Defines the dictionary of textures.
  47996. *
  47997. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  47998. * @return {NodeLoader} A reference to this loader.
  47999. */
  48000. setTextures( value ) {
  48001. this.textures = value;
  48002. return this;
  48003. }
  48004. /**
  48005. * Defines the dictionary of node types.
  48006. *
  48007. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48008. * @return {NodeLoader} A reference to this loader.
  48009. */
  48010. setNodes( value ) {
  48011. this.nodes = value;
  48012. return this;
  48013. }
  48014. /**
  48015. * Creates a node object from the given type.
  48016. *
  48017. * @param {String} type - The node type.
  48018. * @return {Node} The created node instance.
  48019. */
  48020. createNodeFromType( type ) {
  48021. if ( this.nodes[ type ] === undefined ) {
  48022. console.error( 'THREE.NodeLoader: Node type not found:', type );
  48023. return float();
  48024. }
  48025. return nodeObject( new this.nodes[ type ]() );
  48026. }
  48027. }
  48028. /**
  48029. * A special type of material loader for loading node materials.
  48030. *
  48031. * @augments MaterialLoader
  48032. */
  48033. class NodeMaterialLoader extends MaterialLoader {
  48034. /**
  48035. * Constructs a new node material loader.
  48036. *
  48037. * @param {LoadingManager?} manager - A reference to a loading manager.
  48038. */
  48039. constructor( manager ) {
  48040. super( manager );
  48041. /**
  48042. * Represents a dictionary of node types.
  48043. *
  48044. * @type {Object<String,Node.constructor>}
  48045. */
  48046. this.nodes = {};
  48047. /**
  48048. * Represents a dictionary of node material types.
  48049. *
  48050. * @type {Object<String,NodeMaterial.constructor>}
  48051. */
  48052. this.nodeMaterials = {};
  48053. }
  48054. /**
  48055. * Parses the node material from the given JSON.
  48056. *
  48057. * @param {Object} json - The JSON definition
  48058. * @return {NodeMaterial}. The parsed material.
  48059. */
  48060. parse( json ) {
  48061. const material = super.parse( json );
  48062. const nodes = this.nodes;
  48063. const inputNodes = json.inputNodes;
  48064. for ( const property in inputNodes ) {
  48065. const uuid = inputNodes[ property ];
  48066. material[ property ] = nodes[ uuid ];
  48067. }
  48068. return material;
  48069. }
  48070. /**
  48071. * Defines the dictionary of node types.
  48072. *
  48073. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48074. * @return {NodeLoader} A reference to this loader.
  48075. */
  48076. setNodes( value ) {
  48077. this.nodes = value;
  48078. return this;
  48079. }
  48080. /**
  48081. * Defines the dictionary of node material types.
  48082. *
  48083. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48084. * @return {NodeLoader} A reference to this loader.
  48085. */
  48086. setNodeMaterials( value ) {
  48087. this.nodeMaterials = value;
  48088. return this;
  48089. }
  48090. /**
  48091. * Creates a node material from the given type.
  48092. *
  48093. * @param {String} type - The node material type.
  48094. * @return {Node} The created node material instance.
  48095. */
  48096. createMaterialFromType( type ) {
  48097. const materialClass = this.nodeMaterials[ type ];
  48098. if ( materialClass !== undefined ) {
  48099. return new materialClass();
  48100. }
  48101. return super.createMaterialFromType( type );
  48102. }
  48103. }
  48104. /**
  48105. * A special type of object loader for loading 3D objects using
  48106. * node materials.
  48107. *
  48108. * @augments ObjectLoader
  48109. */
  48110. class NodeObjectLoader extends ObjectLoader {
  48111. /**
  48112. * Constructs a new node object loader.
  48113. *
  48114. * @param {LoadingManager?} manager - A reference to a loading manager.
  48115. */
  48116. constructor( manager ) {
  48117. super( manager );
  48118. /**
  48119. * Represents a dictionary of node types.
  48120. *
  48121. * @type {Object<String,Node.constructor>}
  48122. */
  48123. this.nodes = {};
  48124. /**
  48125. * Represents a dictionary of node material types.
  48126. *
  48127. * @type {Object<String,NodeMaterial.constructor>}
  48128. */
  48129. this.nodeMaterials = {};
  48130. /**
  48131. * A reference to hold the `nodes` JSON property.
  48132. *
  48133. * @private
  48134. * @type {Object?}
  48135. */
  48136. this._nodesJSON = null;
  48137. }
  48138. /**
  48139. * Defines the dictionary of node types.
  48140. *
  48141. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48142. * @return {NodeLoader} A reference to this loader.
  48143. */
  48144. setNodes( value ) {
  48145. this.nodes = value;
  48146. return this;
  48147. }
  48148. /**
  48149. * Defines the dictionary of node material types.
  48150. *
  48151. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48152. * @return {NodeLoader} A reference to this loader.
  48153. */
  48154. setNodeMaterials( value ) {
  48155. this.nodeMaterials = value;
  48156. return this;
  48157. }
  48158. /**
  48159. * Parses the node objects from the given JSON.
  48160. *
  48161. * @param {Object} json - The JSON definition
  48162. * @param {Function} onLoad - The onLoad callback function.
  48163. * @return {Object3D}. The parsed 3D object.
  48164. */
  48165. parse( json, onLoad ) {
  48166. this._nodesJSON = json.nodes;
  48167. const data = super.parse( json, onLoad );
  48168. this._nodesJSON = null; // dispose
  48169. return data;
  48170. }
  48171. /**
  48172. * Parses the node objects from the given JSON and textures.
  48173. *
  48174. * @param {Object} json - The JSON definition
  48175. * @param {Object<String,Texture>} textures - The texture library.
  48176. * @return {Object<String,Node>}. The parsed nodes.
  48177. */
  48178. parseNodes( json, textures ) {
  48179. if ( json !== undefined ) {
  48180. const loader = new NodeLoader();
  48181. loader.setNodes( this.nodes );
  48182. loader.setTextures( textures );
  48183. return loader.parseNodes( json );
  48184. }
  48185. return {};
  48186. }
  48187. /**
  48188. * Parses the node objects from the given JSON and textures.
  48189. *
  48190. * @param {Object} json - The JSON definition
  48191. * @param {Object<String,Texture>} textures - The texture library.
  48192. * @return {Object<String,NodeMaterial>}. The parsed materials.
  48193. */
  48194. parseMaterials( json, textures ) {
  48195. const materials = {};
  48196. if ( json !== undefined ) {
  48197. const nodes = this.parseNodes( this._nodesJSON, textures );
  48198. const loader = new NodeMaterialLoader();
  48199. loader.setTextures( textures );
  48200. loader.setNodes( nodes );
  48201. loader.setNodeMaterials( this.nodeMaterials );
  48202. for ( let i = 0, l = json.length; i < l; i ++ ) {
  48203. const data = json[ i ];
  48204. materials[ data.uuid ] = loader.parse( data );
  48205. }
  48206. }
  48207. return materials;
  48208. }
  48209. }
  48210. /**
  48211. * In earlier three.js versions, clipping was defined globally
  48212. * on the renderer or on material level. This special version of
  48213. * `THREE.Group` allows to encode the clipping state into the scene
  48214. * graph. Meaning if you create an instance of this group, all
  48215. * descendant 3D objects will be affected by the respective clipping
  48216. * planes.
  48217. *
  48218. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  48219. *
  48220. * @augments Group
  48221. */
  48222. class ClippingGroup extends Group {
  48223. /**
  48224. * Constructs a new clipping group.
  48225. */
  48226. constructor() {
  48227. super();
  48228. /**
  48229. * This flag can be used for type testing.
  48230. *
  48231. * @type {Boolean}
  48232. * @readonly
  48233. * @default true
  48234. */
  48235. this.isClippingGroup = true;
  48236. /**
  48237. * An array with clipping planes.
  48238. *
  48239. * @type {Array<Plane>}
  48240. */
  48241. this.clippingPlanes = [];
  48242. /**
  48243. * Whether clipping should be enabled or not.
  48244. *
  48245. * @type {Boolean}
  48246. * @default true
  48247. */
  48248. this.enabled = true;
  48249. /**
  48250. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  48251. *
  48252. * @type {Boolean}
  48253. * @default false
  48254. */
  48255. this.clipIntersection = false;
  48256. /**
  48257. * Whether shadows should be clipped or not.
  48258. *
  48259. * @type {Boolean}
  48260. * @default false
  48261. */
  48262. this.clipShadows = false;
  48263. }
  48264. }
  48265. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号