three.webgpu.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636
  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.varying( '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( 'varying', varying );
  4718. addMethodChaining( 'vertexStage', vertexStage );
  4719. /** @module ColorSpaceFunctions **/
  4720. /**
  4721. * Converts the given color value from sRGB to linear-sRGB color space.
  4722. *
  4723. * @method
  4724. * @param {Node<vec3>} color - The sRGB color.
  4725. * @return {Node<vec3>} The linear-sRGB color.
  4726. */
  4727. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4728. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4729. const b = color.mul( 0.0773993808 );
  4730. const factor = color.lessThanEqual( 0.04045 );
  4731. const rgbResult = mix( a, b, factor );
  4732. return rgbResult;
  4733. } ).setLayout( {
  4734. name: 'sRGBTransferEOTF',
  4735. type: 'vec3',
  4736. inputs: [
  4737. { name: 'color', type: 'vec3' }
  4738. ]
  4739. } );
  4740. /**
  4741. * Converts the given color value from linear-sRGB to sRGB color space.
  4742. *
  4743. * @method
  4744. * @param {Node<vec3>} color - The linear-sRGB color.
  4745. * @return {Node<vec3>} The sRGB color.
  4746. */
  4747. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4748. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4749. const b = color.mul( 12.92 );
  4750. const factor = color.lessThanEqual( 0.0031308 );
  4751. const rgbResult = mix( a, b, factor );
  4752. return rgbResult;
  4753. } ).setLayout( {
  4754. name: 'sRGBTransferOETF',
  4755. type: 'vec3',
  4756. inputs: [
  4757. { name: 'color', type: 'vec3' }
  4758. ]
  4759. } );
  4760. /** @module ColorSpaceNode **/
  4761. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4762. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4763. /**
  4764. * This node represents a color space conversion. Meaning it converts
  4765. * a color value from a source to a target color space.
  4766. *
  4767. * @augments TempNode
  4768. */
  4769. class ColorSpaceNode extends TempNode {
  4770. static get type() {
  4771. return 'ColorSpaceNode';
  4772. }
  4773. /**
  4774. * Constructs a new color space node.
  4775. *
  4776. * @param {Node} colorNode - Represents the color to convert.
  4777. * @param {String} source - The source color space.
  4778. * @param {String} target - The target color space.
  4779. */
  4780. constructor( colorNode, source, target ) {
  4781. super( 'vec4' );
  4782. /**
  4783. * Represents the color to convert.
  4784. *
  4785. * @type {Node}
  4786. */
  4787. this.colorNode = colorNode;
  4788. /**
  4789. * The source color space.
  4790. *
  4791. * @type {String}
  4792. */
  4793. this.source = source;
  4794. /**
  4795. * The target color space.
  4796. *
  4797. * @type {String}
  4798. */
  4799. this.target = target;
  4800. }
  4801. /**
  4802. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4803. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4804. * color management and renderer.
  4805. *
  4806. * @param {NodeBuilder} builder - The current node builder.
  4807. * @param {String} colorSpace - The color space to resolve.
  4808. * @return {String} The resolved color space.
  4809. */
  4810. resolveColorSpace( builder, colorSpace ) {
  4811. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4812. return ColorManagement.workingColorSpace;
  4813. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4814. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4815. }
  4816. return colorSpace;
  4817. }
  4818. setup( builder ) {
  4819. const { colorNode } = this;
  4820. const source = this.resolveColorSpace( builder, this.source );
  4821. const target = this.resolveColorSpace( builder, this.target );
  4822. let outputNode = colorNode;
  4823. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4824. return outputNode;
  4825. }
  4826. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4827. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4828. }
  4829. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4830. outputNode = vec4(
  4831. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4832. outputNode.a
  4833. );
  4834. }
  4835. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4836. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4837. }
  4838. return outputNode;
  4839. }
  4840. }
  4841. /**
  4842. * TSL function for converting a given color node to the current output color space.
  4843. *
  4844. * @function
  4845. * @param {Node} node - Represents the node to convert.
  4846. * @returns {ColorSpaceNode}
  4847. */
  4848. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4849. /**
  4850. * TSL function for converting a given color node to the current working color space.
  4851. *
  4852. * @function
  4853. * @param {Node} node - Represents the node to convert.
  4854. * @returns {ColorSpaceNode}
  4855. */
  4856. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4857. /**
  4858. * TSL function for converting a given color node from the current working color space to the given color space.
  4859. *
  4860. * @function
  4861. * @param {Node} node - Represents the node to convert.
  4862. * @param {String} colorSpace - The target color space.
  4863. * @returns {ColorSpaceNode}
  4864. */
  4865. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4866. /**
  4867. * TSL function for converting a given color node from the given color space to the current working color space.
  4868. *
  4869. * @function
  4870. * @param {Node} node - Represents the node to convert.
  4871. * @param {String} colorSpace - The source color space.
  4872. * @returns {ColorSpaceNode}
  4873. */
  4874. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4875. /**
  4876. * TSL function for converting a given color node from one color space to another one.
  4877. *
  4878. * @function
  4879. * @param {Node} node - Represents the node to convert.
  4880. * @param {String} sourceColorSpace - The source color space.
  4881. * @param {String} targetColorSpace - The target color space.
  4882. * @returns {ColorSpaceNode}
  4883. */
  4884. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4885. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4886. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4887. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4888. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4889. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4890. /** @module ReferenceBaseNode **/
  4891. /**
  4892. * This class is only relevant if the referenced property is array-like.
  4893. * In this case, `ReferenceElementNode` allows to refer to a specific
  4894. * element inside the data structure via an index.
  4895. *
  4896. * @augments ArrayElementNode
  4897. */
  4898. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4899. static get type() {
  4900. return 'ReferenceElementNode';
  4901. }
  4902. /**
  4903. * Constructs a new reference element node.
  4904. *
  4905. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  4906. * @param {Node} indexNode - The index node that defines the element access.
  4907. */
  4908. constructor( referenceNode, indexNode ) {
  4909. super( referenceNode, indexNode );
  4910. /**
  4911. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4912. * property references to the current node.
  4913. *
  4914. * @type {ReferenceBaseNode?}
  4915. * @default null
  4916. */
  4917. this.referenceNode = referenceNode;
  4918. /**
  4919. * This flag can be used for type testing.
  4920. *
  4921. * @type {Boolean}
  4922. * @readonly
  4923. * @default true
  4924. */
  4925. this.isReferenceElementNode = true;
  4926. }
  4927. /**
  4928. * This method is overwritten since the node type is inferred from
  4929. * the uniform type of the reference node.
  4930. *
  4931. * @return {String} The node type.
  4932. */
  4933. getNodeType() {
  4934. return this.referenceNode.uniformType;
  4935. }
  4936. generate( builder ) {
  4937. const snippet = super.generate( builder );
  4938. const arrayType = this.referenceNode.getNodeType();
  4939. const elementType = this.getNodeType();
  4940. return builder.format( snippet, arrayType, elementType );
  4941. }
  4942. };
  4943. /**
  4944. * Base class for nodes which establishes a reference to a property of another object.
  4945. * In this way, the value of the node is automatically linked to the value of
  4946. * referenced object. Reference nodes internally represent the linked value
  4947. * as a uniform.
  4948. *
  4949. * @augments Node
  4950. */
  4951. class ReferenceBaseNode extends Node {
  4952. static get type() {
  4953. return 'ReferenceBaseNode';
  4954. }
  4955. /**
  4956. * Constructs a new reference base node.
  4957. *
  4958. * @param {String} property - The name of the property the node refers to.
  4959. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4960. * @param {Object?} [object=null] - The object the property belongs to.
  4961. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4962. */
  4963. constructor( property, uniformType, object = null, count = null ) {
  4964. super();
  4965. /**
  4966. * The name of the property the node refers to.
  4967. *
  4968. * @type {String}
  4969. */
  4970. this.property = property;
  4971. /**
  4972. * The uniform type that should be used to represent the property value.
  4973. *
  4974. * @type {String}
  4975. */
  4976. this.uniformType = uniformType;
  4977. /**
  4978. * The object the property belongs to.
  4979. *
  4980. * @type {Object?}
  4981. * @default null
  4982. */
  4983. this.object = object;
  4984. /**
  4985. * When the linked property is an array, this parameter defines its length.
  4986. *
  4987. * @type {Number?}
  4988. * @default null
  4989. */
  4990. this.count = count;
  4991. /**
  4992. * The property name might have dots so nested properties can be referred.
  4993. * The hierarchy of the names is stored inside this array.
  4994. *
  4995. * @type {Array<String>}
  4996. */
  4997. this.properties = property.split( '.' );
  4998. /**
  4999. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5000. * since the final reference might be updated from calling code.
  5001. *
  5002. * @type {Object?}
  5003. * @default null
  5004. */
  5005. this.reference = object;
  5006. /**
  5007. * The uniform node that holds the value of the reference node.
  5008. *
  5009. * @type {UniformNode}
  5010. * @default null
  5011. */
  5012. this.node = null;
  5013. /**
  5014. * The uniform group of the internal uniform.
  5015. *
  5016. * @type {UniformGroupNode}
  5017. * @default null
  5018. */
  5019. this.group = null;
  5020. /**
  5021. * Overwritten since reference nodes are updated per object.
  5022. *
  5023. * @type {String}
  5024. * @default 'object'
  5025. */
  5026. this.updateType = NodeUpdateType.OBJECT;
  5027. }
  5028. /**
  5029. * Sets the uniform group for this reference node.
  5030. *
  5031. * @param {UniformGroupNode} group - The uniform group to set.
  5032. * @return {ReferenceBaseNode} A reference to this node.
  5033. */
  5034. setGroup( group ) {
  5035. this.group = group;
  5036. return this;
  5037. }
  5038. /**
  5039. * When the referred property is array-like, this method can be used
  5040. * to access elements via an index node.
  5041. *
  5042. * @param {IndexNode} indexNode - indexNode.
  5043. * @return {ReferenceElementNode} A reference to an element.
  5044. */
  5045. element( indexNode ) {
  5046. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5047. }
  5048. /**
  5049. * Sets the node type which automatically defines the internal
  5050. * uniform type.
  5051. *
  5052. * @param {String} uniformType - The type to set.
  5053. */
  5054. setNodeType( uniformType ) {
  5055. const node = uniform( null, uniformType ).getSelf();
  5056. if ( this.group !== null ) {
  5057. node.setGroup( this.group );
  5058. }
  5059. this.node = node;
  5060. }
  5061. /**
  5062. * This method is overwritten since the node type is inferred from
  5063. * the type of the reference node.
  5064. *
  5065. * @param {NodeBuilder} builder - The current node builder.
  5066. * @return {String} The node type.
  5067. */
  5068. getNodeType( builder ) {
  5069. if ( this.node === null ) {
  5070. this.updateReference( builder );
  5071. this.updateValue();
  5072. }
  5073. return this.node.getNodeType( builder );
  5074. }
  5075. /**
  5076. * Returns the property value from the given referred object.
  5077. *
  5078. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5079. * @return {Any} The value.
  5080. */
  5081. getValueFromReference( object = this.reference ) {
  5082. const { properties } = this;
  5083. let value = object[ properties[ 0 ] ];
  5084. for ( let i = 1; i < properties.length; i ++ ) {
  5085. value = value[ properties[ i ] ];
  5086. }
  5087. return value;
  5088. }
  5089. /**
  5090. * Allows to update the reference based on the given state. The state is only
  5091. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5092. *
  5093. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5094. * @return {Object} The updated reference.
  5095. */
  5096. updateReference( state ) {
  5097. this.reference = this.object !== null ? this.object : state.object;
  5098. return this.reference;
  5099. }
  5100. /**
  5101. * The output of the reference node is the internal uniform node.
  5102. *
  5103. * @return {UniformNode} The output node.
  5104. */
  5105. setup() {
  5106. this.updateValue();
  5107. return this.node;
  5108. }
  5109. /**
  5110. * Overwritten to to update the internal uniform value.
  5111. *
  5112. * @param {NodeFrame} frame - A reference to the current node frame.
  5113. */
  5114. update( /*frame*/ ) {
  5115. this.updateValue();
  5116. }
  5117. /**
  5118. * Retrieves the value from the referred object property and uses it
  5119. * to updated the internal uniform.
  5120. */
  5121. updateValue() {
  5122. if ( this.node === null ) this.setNodeType( this.uniformType );
  5123. const value = this.getValueFromReference();
  5124. if ( Array.isArray( value ) ) {
  5125. this.node.array = value;
  5126. } else {
  5127. this.node.value = value;
  5128. }
  5129. }
  5130. }
  5131. /**
  5132. * TSL function for creating a reference base node.
  5133. *
  5134. * @function
  5135. * @param {String} name - The name of the property the node refers to.
  5136. * @param {String} type - The uniform type that should be used to represent the property value.
  5137. * @param {Object} object - The object the property belongs to.
  5138. * @returns {ReferenceBaseNode}
  5139. */
  5140. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5141. /** @module RendererReferenceNode **/
  5142. /**
  5143. * This node is a special type of reference node which is intended
  5144. * for linking renderer properties with node values.
  5145. * ```js
  5146. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5147. * ```
  5148. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5149. * automatically be updated.
  5150. *
  5151. * @augments ReferenceBaseNode
  5152. */
  5153. class RendererReferenceNode extends ReferenceBaseNode {
  5154. static get type() {
  5155. return 'RendererReferenceNode';
  5156. }
  5157. /**
  5158. * Constructs a new renderer reference node.
  5159. *
  5160. * @param {String} property - The name of the property the node refers to.
  5161. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5162. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5163. * the node refers to the renderer of the current state.
  5164. */
  5165. constructor( property, inputType, renderer = null ) {
  5166. super( property, inputType, renderer );
  5167. /**
  5168. * The renderer the property belongs to. When no renderer is set,
  5169. * the node refers to the renderer of the current state.
  5170. *
  5171. * @type {Renderer?}
  5172. * @default null
  5173. */
  5174. this.renderer = renderer;
  5175. this.setGroup( renderGroup );
  5176. }
  5177. /**
  5178. * Updates the reference based on the given state. The state is only evaluated
  5179. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5180. *
  5181. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5182. * @return {Object} The updated reference.
  5183. */
  5184. updateReference( state ) {
  5185. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5186. return this.reference;
  5187. }
  5188. }
  5189. /**
  5190. * TSL function for creating a renderer reference node.
  5191. *
  5192. * @function
  5193. * @param {String} name - The name of the property the node refers to.
  5194. * @param {String} type - The uniform type that should be used to represent the property value.
  5195. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5196. * the node refers to the renderer of the current state.
  5197. * @returns {RendererReferenceNode}
  5198. */
  5199. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5200. /** @module ToneMappingNode **/
  5201. /**
  5202. * This node represents a tone mapping operation.
  5203. *
  5204. * @augments TempNode
  5205. */
  5206. class ToneMappingNode extends TempNode {
  5207. static get type() {
  5208. return 'ToneMappingNode';
  5209. }
  5210. /**
  5211. * Constructs a new tone mapping node.
  5212. *
  5213. * @param {Number} toneMapping - The tone mapping type.
  5214. * @param {Node} exposureNode - The tone mapping exposure.
  5215. * @param {Node} [colorNode=null] - The color node to process.
  5216. */
  5217. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5218. super( 'vec3' );
  5219. /**
  5220. * The tone mapping type.
  5221. *
  5222. * @type {Number}
  5223. */
  5224. this.toneMapping = toneMapping;
  5225. /**
  5226. * The tone mapping exposure.
  5227. *
  5228. * @type {Node}
  5229. * @default null
  5230. */
  5231. this.exposureNode = exposureNode;
  5232. /**
  5233. * Represents the color to process.
  5234. *
  5235. * @type {Node?}
  5236. * @default null
  5237. */
  5238. this.colorNode = colorNode;
  5239. }
  5240. /**
  5241. * Overwrites the default `customCacheKey()` implementation by including the tone
  5242. * mapping type into the cache key.
  5243. *
  5244. * @return {Number} The hash.
  5245. */
  5246. customCacheKey() {
  5247. return hash$1( this.toneMapping );
  5248. }
  5249. setup( builder ) {
  5250. const colorNode = this.colorNode || builder.context.color;
  5251. const toneMapping = this.toneMapping;
  5252. if ( toneMapping === NoToneMapping ) return colorNode;
  5253. let outputNode = null;
  5254. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5255. if ( toneMappingFn !== null ) {
  5256. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5257. } else {
  5258. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5259. outputNode = colorNode;
  5260. }
  5261. return outputNode;
  5262. }
  5263. }
  5264. /**
  5265. * TSL function for creating a tone mapping node.
  5266. *
  5267. * @function
  5268. * @param {Number} mapping - The tone mapping type.
  5269. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5270. * @param {Node<vec3> | Color} color - The color node to process.
  5271. * @returns {ToneMappingNode<vec3>}
  5272. */
  5273. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5274. /**
  5275. * TSL object that represents the global tone mapping exposure of the renderer.
  5276. *
  5277. * @type {RendererReferenceNode<vec3>}
  5278. */
  5279. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5280. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5281. /** @module BufferAttributeNode **/
  5282. /**
  5283. * In earlier `three.js` versions it was only possible to define attribute data
  5284. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5285. * on the node level.
  5286. * ```js
  5287. * const geometry = new THREE.PlaneGeometry();
  5288. * const positionAttribute = geometry.getAttribute( 'position' );
  5289. *
  5290. * const colors = [];
  5291. * for ( let i = 0; i < position.count; i ++ ) {
  5292. * colors.push( 1, 0, 0 );
  5293. * }
  5294. *
  5295. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5296. * ```
  5297. * This new approach is especially interesting when geometry data are generated via
  5298. * compute shaders. The below line converts a storage buffer into an attribute node.
  5299. * ```js
  5300. * material.positionNode = positionBuffer.toAttribute();
  5301. * ```
  5302. * @augments InputNode
  5303. */
  5304. class BufferAttributeNode extends InputNode {
  5305. static get type() {
  5306. return 'BufferAttributeNode';
  5307. }
  5308. /**
  5309. * Constructs a new buffer attribute node.
  5310. *
  5311. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5312. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5313. * @param {Number} [bufferStride=0] - The buffer stride.
  5314. * @param {Number} [bufferOffset=0] - The buffer offset.
  5315. */
  5316. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5317. super( value, bufferType );
  5318. /**
  5319. * This flag can be used for type testing.
  5320. *
  5321. * @type {Boolean}
  5322. * @readonly
  5323. * @default true
  5324. */
  5325. this.isBufferNode = true;
  5326. /**
  5327. * The buffer type (e.g. `'vec3'`).
  5328. *
  5329. * @type {String}
  5330. * @default null
  5331. */
  5332. this.bufferType = bufferType;
  5333. /**
  5334. * The buffer stride.
  5335. *
  5336. * @type {Number}
  5337. * @default 0
  5338. */
  5339. this.bufferStride = bufferStride;
  5340. /**
  5341. * The buffer offset.
  5342. *
  5343. * @type {Number}
  5344. * @default 0
  5345. */
  5346. this.bufferOffset = bufferOffset;
  5347. /**
  5348. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5349. * if you are planning to update the attribute data per frame.
  5350. *
  5351. * @type {Number}
  5352. * @default StaticDrawUsage
  5353. */
  5354. this.usage = StaticDrawUsage;
  5355. /**
  5356. * Whether the attribute is instanced or not.
  5357. *
  5358. * @type {Boolean}
  5359. * @default false
  5360. */
  5361. this.instanced = false;
  5362. /**
  5363. * A reference to the buffer attribute.
  5364. *
  5365. * @type {BufferAttribute?}
  5366. * @default null
  5367. */
  5368. this.attribute = null;
  5369. /**
  5370. * `BufferAttributeNode` sets this property to `true` by default.
  5371. *
  5372. * @type {Boolean}
  5373. * @default true
  5374. */
  5375. this.global = true;
  5376. if ( value && value.isBufferAttribute === true ) {
  5377. this.attribute = value;
  5378. this.usage = value.usage;
  5379. this.instanced = value.isInstancedBufferAttribute;
  5380. }
  5381. }
  5382. /**
  5383. * This method is overwritten since the attribute data might be shared
  5384. * and thus the hash should be shared as well.
  5385. *
  5386. * @param {NodeBuilder} builder - The current node builder.
  5387. * @return {String} The hash.
  5388. */
  5389. getHash( builder ) {
  5390. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5391. let bufferData = builder.globalCache.getData( this.value );
  5392. if ( bufferData === undefined ) {
  5393. bufferData = {
  5394. node: this
  5395. };
  5396. builder.globalCache.setData( this.value, bufferData );
  5397. }
  5398. return bufferData.node.uuid;
  5399. }
  5400. return this.uuid;
  5401. }
  5402. /**
  5403. * This method is overwritten since the node type is inferred from
  5404. * the buffer attribute.
  5405. *
  5406. * @param {NodeBuilder} builder - The current node builder.
  5407. * @return {String} The node type.
  5408. */
  5409. getNodeType( builder ) {
  5410. if ( this.bufferType === null ) {
  5411. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5412. }
  5413. return this.bufferType;
  5414. }
  5415. /**
  5416. * Depending on which value was passed to the node, `setup()` behaves
  5417. * differently. If no instance of `BufferAttribute` was passed, the method
  5418. * creates an internal attribute and configures it respectively.
  5419. *
  5420. * @param {NodeBuilder} builder - The current node builder.
  5421. */
  5422. setup( builder ) {
  5423. if ( this.attribute !== null ) return;
  5424. const type = this.getNodeType( builder );
  5425. const array = this.value;
  5426. const itemSize = builder.getTypeLength( type );
  5427. const stride = this.bufferStride || itemSize;
  5428. const offset = this.bufferOffset;
  5429. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5430. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5431. buffer.setUsage( this.usage );
  5432. this.attribute = bufferAttribute;
  5433. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5434. }
  5435. /**
  5436. * Generates the code snippet of the buffer attribute node.
  5437. *
  5438. * @param {NodeBuilder} builder - The current node builder.
  5439. * @return {String} The generated code snippet.
  5440. */
  5441. generate( builder ) {
  5442. const nodeType = this.getNodeType( builder );
  5443. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5444. const propertyName = builder.getPropertyName( nodeAttribute );
  5445. let output = null;
  5446. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5447. this.name = propertyName;
  5448. output = propertyName;
  5449. } else {
  5450. const nodeVarying = varying( this );
  5451. output = nodeVarying.build( builder, nodeType );
  5452. }
  5453. return output;
  5454. }
  5455. /**
  5456. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5457. *
  5458. * @param {NodeBuilder} builder - The current node builder.
  5459. * @return {String} The input type.
  5460. */
  5461. getInputType( /*builder*/ ) {
  5462. return 'bufferAttribute';
  5463. }
  5464. /**
  5465. * Sets the `usage` property to the given value.
  5466. *
  5467. * @param {Number} value - The usage to set.
  5468. * @return {BufferAttributeNode} A reference to this node.
  5469. */
  5470. setUsage( value ) {
  5471. this.usage = value;
  5472. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5473. this.attribute.usage = value;
  5474. }
  5475. return this;
  5476. }
  5477. /**
  5478. * Sets the `instanced` property to the given value.
  5479. *
  5480. * @param {Boolean} value - The value to set.
  5481. * @return {BufferAttributeNode} A reference to this node.
  5482. */
  5483. setInstanced( value ) {
  5484. this.instanced = value;
  5485. return this;
  5486. }
  5487. }
  5488. /**
  5489. * TSL function for creating a buffer attribute node.
  5490. *
  5491. * @function
  5492. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5493. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5494. * @param {Number} [stride=0] - The buffer stride.
  5495. * @param {Number} [offset=0] - The buffer offset.
  5496. * @returns {BufferAttributeNode}
  5497. */
  5498. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5499. /**
  5500. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5501. * Use this function if attribute data are updated per frame.
  5502. *
  5503. * @function
  5504. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5505. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5506. * @param {Number} [stride=0] - The buffer stride.
  5507. * @param {Number} [offset=0] - The buffer offset.
  5508. * @returns {BufferAttributeNode}
  5509. */
  5510. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5511. /**
  5512. * TSL function for creating a buffer attribute node but with enabled instancing
  5513. *
  5514. * @function
  5515. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5516. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5517. * @param {Number} [stride=0] - The buffer stride.
  5518. * @param {Number} [offset=0] - The buffer offset.
  5519. * @returns {BufferAttributeNode}
  5520. */
  5521. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5522. /**
  5523. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5524. *
  5525. * @function
  5526. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5527. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5528. * @param {Number} [stride=0] - The buffer stride.
  5529. * @param {Number} [offset=0] - The buffer offset.
  5530. * @returns {BufferAttributeNode}
  5531. */
  5532. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5533. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5534. /** @module ComputeNode **/
  5535. /**
  5536. * TODO
  5537. *
  5538. * @augments Node
  5539. */
  5540. class ComputeNode extends Node {
  5541. static get type() {
  5542. return 'ComputeNode';
  5543. }
  5544. /**
  5545. * Constructs a new compute node.
  5546. *
  5547. * @param {Node} computeNode - TODO
  5548. * @param {Number} count - TODO.
  5549. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5550. */
  5551. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5552. super( 'void' );
  5553. /**
  5554. * This flag can be used for type testing.
  5555. *
  5556. * @type {Boolean}
  5557. * @readonly
  5558. * @default true
  5559. */
  5560. this.isComputeNode = true;
  5561. /**
  5562. * TODO
  5563. *
  5564. * @type {Node}
  5565. */
  5566. this.computeNode = computeNode;
  5567. /**
  5568. * TODO
  5569. *
  5570. * @type {Number}
  5571. */
  5572. this.count = count;
  5573. /**
  5574. * TODO
  5575. *
  5576. * @type {Array<Number>}
  5577. * @default [64]
  5578. */
  5579. this.workgroupSize = workgroupSize;
  5580. /**
  5581. * TODO
  5582. *
  5583. * @type {Number}
  5584. */
  5585. this.dispatchCount = 0;
  5586. /**
  5587. * TODO
  5588. *
  5589. * @type {Number}
  5590. */
  5591. this.version = 1;
  5592. /**
  5593. * The name or label of the uniform.
  5594. *
  5595. * @type {String}
  5596. * @default ''
  5597. */
  5598. this.name = '';
  5599. /**
  5600. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5601. * is executed once per object by default.
  5602. *
  5603. * @type {String}
  5604. * @default 'object'
  5605. */
  5606. this.updateBeforeType = NodeUpdateType.OBJECT;
  5607. /**
  5608. * TODO
  5609. *
  5610. * @type {Function}
  5611. */
  5612. this.onInitFunction = null;
  5613. this.updateDispatchCount();
  5614. }
  5615. /**
  5616. * Executes the `dispose` event for this node.
  5617. */
  5618. dispose() {
  5619. this.dispatchEvent( { type: 'dispose' } );
  5620. }
  5621. /**
  5622. * Sets the {@link ComputeNode#name} property.
  5623. *
  5624. * @param {String} name - The name of the uniform.
  5625. * @return {ComputeNode} A reference to this node.
  5626. */
  5627. label( name ) {
  5628. this.name = name;
  5629. return this;
  5630. }
  5631. /**
  5632. * TODO
  5633. */
  5634. updateDispatchCount() {
  5635. const { count, workgroupSize } = this;
  5636. let size = workgroupSize[ 0 ];
  5637. for ( let i = 1; i < workgroupSize.length; i ++ )
  5638. size *= workgroupSize[ i ];
  5639. this.dispatchCount = Math.ceil( count / size );
  5640. }
  5641. /**
  5642. * TODO
  5643. *
  5644. * @param {Function} callback - TODO.
  5645. * @return {ComputeNode} A reference to this node.
  5646. */
  5647. onInit( callback ) {
  5648. this.onInitFunction = callback;
  5649. return this;
  5650. }
  5651. /**
  5652. * The method execute the compute for this node.
  5653. *
  5654. * @param {NodeFrame} frame - A reference to the current node frame.
  5655. */
  5656. updateBefore( { renderer } ) {
  5657. renderer.compute( this );
  5658. }
  5659. generate( builder ) {
  5660. const { shaderStage } = builder;
  5661. if ( shaderStage === 'compute' ) {
  5662. const snippet = this.computeNode.build( builder, 'void' );
  5663. if ( snippet !== '' ) {
  5664. builder.addLineFlowCode( snippet, this );
  5665. }
  5666. }
  5667. }
  5668. }
  5669. /**
  5670. * TSL function for creating a compute node.
  5671. *
  5672. * @function
  5673. * @param {Node} node - TODO
  5674. * @param {Number} count - TODO.
  5675. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5676. * @returns {AtomicFunctionNode}
  5677. */
  5678. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5679. addMethodChaining( 'compute', compute );
  5680. /** @module CacheNode **/
  5681. /**
  5682. * This node can be used as a cache management component for another node.
  5683. * Caching is in general used by default in {@link NodeBuilder} but this node
  5684. * allows the usage of a shared parent cache during the build process.
  5685. *
  5686. * @augments Node
  5687. */
  5688. class CacheNode extends Node {
  5689. static get type() {
  5690. return 'CacheNode';
  5691. }
  5692. /**
  5693. * Constructs a new cache node.
  5694. *
  5695. * @param {Node} node - The node that should be cached.
  5696. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5697. */
  5698. constructor( node, parent = true ) {
  5699. super();
  5700. /**
  5701. * The node that should be cached.
  5702. *
  5703. * @type {Node}
  5704. */
  5705. this.node = node;
  5706. /**
  5707. * Whether this node refers to a shared parent cache or not.
  5708. *
  5709. * @type {Boolean}
  5710. * @default true
  5711. */
  5712. this.parent = parent;
  5713. /**
  5714. * This flag can be used for type testing.
  5715. *
  5716. * @type {Boolean}
  5717. * @readonly
  5718. * @default true
  5719. */
  5720. this.isCacheNode = true;
  5721. }
  5722. getNodeType( builder ) {
  5723. const previousCache = builder.getCache();
  5724. const cache = builder.getCacheFromNode( this, this.parent );
  5725. builder.setCache( cache );
  5726. const nodeType = this.node.getNodeType( builder );
  5727. builder.setCache( previousCache );
  5728. return nodeType;
  5729. }
  5730. build( builder, ...params ) {
  5731. const previousCache = builder.getCache();
  5732. const cache = builder.getCacheFromNode( this, this.parent );
  5733. builder.setCache( cache );
  5734. const data = this.node.build( builder, ...params );
  5735. builder.setCache( previousCache );
  5736. return data;
  5737. }
  5738. }
  5739. /**
  5740. * TSL function for creating a cache node.
  5741. *
  5742. * @function
  5743. * @param {Node} node - The node that should be cached.
  5744. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5745. * @returns {CacheNode}
  5746. */
  5747. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5748. addMethodChaining( 'cache', cache );
  5749. /** @module BypassNode **/
  5750. /**
  5751. * The class generates the code of a given node but returns another node in the output.
  5752. * This can be used to call a method or node that does not return a value, i.e.
  5753. * type `void` on an input where returning a value is required. Example:
  5754. *
  5755. * ```js
  5756. * material.colorNode = myColor.bypass( runVoidFn() )
  5757. *```
  5758. *
  5759. * @augments Node
  5760. */
  5761. class BypassNode extends Node {
  5762. static get type() {
  5763. return 'BypassNode';
  5764. }
  5765. /**
  5766. * Constructs a new bypass node.
  5767. *
  5768. * @param {Node} outputNode - The output node.
  5769. * @param {Node} callNode - The call node.
  5770. */
  5771. constructor( outputNode, callNode ) {
  5772. super();
  5773. /**
  5774. * This flag can be used for type testing.
  5775. *
  5776. * @type {Boolean}
  5777. * @readonly
  5778. * @default true
  5779. */
  5780. this.isBypassNode = true;
  5781. /**
  5782. * The output node.
  5783. *
  5784. * @type {Node}
  5785. */
  5786. this.outputNode = outputNode;
  5787. /**
  5788. * The call node.
  5789. *
  5790. * @type {Node}
  5791. */
  5792. this.callNode = callNode;
  5793. }
  5794. getNodeType( builder ) {
  5795. return this.outputNode.getNodeType( builder );
  5796. }
  5797. generate( builder ) {
  5798. const snippet = this.callNode.build( builder, 'void' );
  5799. if ( snippet !== '' ) {
  5800. builder.addLineFlowCode( snippet, this );
  5801. }
  5802. return this.outputNode.build( builder );
  5803. }
  5804. }
  5805. /**
  5806. * TSL function for creating a bypass node.
  5807. *
  5808. * @function
  5809. * @param {Node} outputNode - The output node.
  5810. * @param {Node} callNode - The call node.
  5811. * @returns {BypassNode}
  5812. */
  5813. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5814. addMethodChaining( 'bypass', bypass );
  5815. /** @module RemapNode **/
  5816. /**
  5817. * This node allows to remap a node value from one range into another. E.g a value of
  5818. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5819. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5820. *
  5821. * @augments Node
  5822. */
  5823. class RemapNode extends Node {
  5824. static get type() {
  5825. return 'RemapNode';
  5826. }
  5827. /**
  5828. * Constructs a new remap node.
  5829. *
  5830. * @param {Node} node - The node that should be remapped.
  5831. * @param {Node} inLowNode - The source or current lower bound of the range.
  5832. * @param {Node} inHighNode - The source or current upper bound of the range.
  5833. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5834. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5835. */
  5836. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5837. super();
  5838. /**
  5839. * The node that should be remapped.
  5840. *
  5841. * @type {Node}
  5842. */
  5843. this.node = node;
  5844. /**
  5845. * The source or current lower bound of the range.
  5846. *
  5847. * @type {Node}
  5848. */
  5849. this.inLowNode = inLowNode;
  5850. /**
  5851. * The source or current upper bound of the range.
  5852. *
  5853. * @type {Node}
  5854. */
  5855. this.inHighNode = inHighNode;
  5856. /**
  5857. * The target lower bound of the range.
  5858. *
  5859. * @type {Node}
  5860. * @default float(0)
  5861. */
  5862. this.outLowNode = outLowNode;
  5863. /**
  5864. * The target upper bound of the range.
  5865. *
  5866. * @type {Node}
  5867. * @default float(1)
  5868. */
  5869. this.outHighNode = outHighNode;
  5870. /**
  5871. * Whether the node value should be clamped before
  5872. * remapping it to the target range.
  5873. *
  5874. * @type {Boolean}
  5875. * @default true
  5876. */
  5877. this.doClamp = true;
  5878. }
  5879. setup() {
  5880. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5881. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5882. if ( doClamp === true ) t = t.clamp();
  5883. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5884. }
  5885. }
  5886. /**
  5887. * TSL function for creating a remap node.
  5888. *
  5889. * @function
  5890. * @param {Node} node - The node that should be remapped.
  5891. * @param {Node} inLowNode - The source or current lower bound of the range.
  5892. * @param {Node} inHighNode - The source or current upper bound of the range.
  5893. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5894. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5895. * @returns {RemapNode}
  5896. */
  5897. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5898. /**
  5899. * TSL function for creating a remap node, but with enabled clamping.
  5900. *
  5901. * @function
  5902. * @param {Node} node - The node that should be remapped.
  5903. * @param {Node} inLowNode - The source or current lower bound of the range.
  5904. * @param {Node} inHighNode - The source or current upper bound of the range.
  5905. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5906. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5907. * @returns {RemapNode}
  5908. */
  5909. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5910. addMethodChaining( 'remap', remap );
  5911. addMethodChaining( 'remapClamp', remapClamp );
  5912. /** @module ExpressionNode **/
  5913. /**
  5914. * This class can be used to implement basic expressions in shader code.
  5915. * Basic examples for that are `return`, `continue` or `discard` statements.
  5916. *
  5917. * @augments Node
  5918. */
  5919. class ExpressionNode extends Node {
  5920. static get type() {
  5921. return 'ExpressionNode';
  5922. }
  5923. /**
  5924. * Constructs a new expression node.
  5925. *
  5926. * @param {String} [snippet=''] - The native code snippet.
  5927. * @param {String} [nodeType='void'] - The node type.
  5928. */
  5929. constructor( snippet = '', nodeType = 'void' ) {
  5930. super( nodeType );
  5931. /**
  5932. * The native code snippet.
  5933. *
  5934. * @type {String}
  5935. * @default ''
  5936. */
  5937. this.snippet = snippet;
  5938. }
  5939. generate( builder, output ) {
  5940. const type = this.getNodeType( builder );
  5941. const snippet = this.snippet;
  5942. if ( type === 'void' ) {
  5943. builder.addLineFlowCode( snippet, this );
  5944. } else {
  5945. return builder.format( `( ${ snippet } )`, type, output );
  5946. }
  5947. }
  5948. }
  5949. /**
  5950. * TSL function for creating an expression node.
  5951. *
  5952. * @function
  5953. * @param {String} [snippet=''] - The native code snippet.
  5954. * @param {String} [nodeType='void'] - The node type.
  5955. * @returns {ExpressionNode}
  5956. */
  5957. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5958. /** @module Discard **/
  5959. /**
  5960. * Represents a `discard` shader operation in TSL.
  5961. *
  5962. * @method
  5963. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5964. * @return {Node} The `discard` expression.
  5965. */
  5966. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5967. /**
  5968. * Represents a `return` shader operation in TSL.
  5969. *
  5970. * @method
  5971. * @return {ExpressionNode} The `return` expression.
  5972. */
  5973. const Return = () => expression( 'return' ).append();
  5974. addMethodChaining( 'discard', Discard );
  5975. /** @module RenderOutputNode **/
  5976. /**
  5977. * Normally, tone mapping and color conversion happens automatically
  5978. * before outputting pixel too the default (screen) framebuffer. In certain
  5979. * post processing setups this happens to late because certain effects
  5980. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5981. * to apply tone mapping and color space conversion at an arbitrary point
  5982. * in the effect chain.
  5983. *
  5984. * When applying tone mapping and color space conversion manually with this node,
  5985. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5986. *
  5987. * ```js
  5988. * const postProcessing = new PostProcessing( renderer );
  5989. * postProcessing.outputColorTransform = false;
  5990. *
  5991. * const scenePass = pass( scene, camera );
  5992. * const outputPass = renderOutput( scenePass );
  5993. *
  5994. * postProcessing.outputNode = outputPass;
  5995. * ```
  5996. *
  5997. * @augments TempNode
  5998. */
  5999. class RenderOutputNode extends TempNode {
  6000. static get type() {
  6001. return 'RenderOutputNode';
  6002. }
  6003. /**
  6004. * Constructs a new render output node.
  6005. *
  6006. * @param {Node} colorNode - The color node to process.
  6007. * @param {Number} toneMapping - The tone mapping type.
  6008. * @param {String} outputColorSpace - The output color space.
  6009. */
  6010. constructor( colorNode, toneMapping, outputColorSpace ) {
  6011. super( 'vec4' );
  6012. /**
  6013. * The color node to process.
  6014. *
  6015. * @type {Node}
  6016. */
  6017. this.colorNode = colorNode;
  6018. /**
  6019. * The tone mapping type.
  6020. *
  6021. * @type {Number?}
  6022. */
  6023. this.toneMapping = toneMapping;
  6024. /**
  6025. * The output color space.
  6026. *
  6027. * @type {String?}
  6028. */
  6029. this.outputColorSpace = outputColorSpace;
  6030. /**
  6031. * This flag can be used for type testing.
  6032. *
  6033. * @type {Boolean}
  6034. * @readonly
  6035. * @default true
  6036. */
  6037. this.isRenderOutputNode = true;
  6038. }
  6039. setup( { context } ) {
  6040. let outputNode = this.colorNode || context.color;
  6041. // tone mapping
  6042. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6043. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6044. if ( toneMapping !== NoToneMapping ) {
  6045. outputNode = outputNode.toneMapping( toneMapping );
  6046. }
  6047. // working to output color space
  6048. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6049. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6050. }
  6051. return outputNode;
  6052. }
  6053. }
  6054. /**
  6055. * TSL function for creating a posterize node.
  6056. *
  6057. * @function
  6058. * @param {Node} color - The color node to process.
  6059. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6060. * @param {String?} [outputColorSpace=null] - The output color space.
  6061. * @returns {RenderOutputNode}
  6062. */
  6063. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6064. addMethodChaining( 'renderOutput', renderOutput );
  6065. // Non-PURE exports list, side-effects are required here.
  6066. // TSL Base Syntax
  6067. function addNodeElement( name/*, nodeElement*/ ) {
  6068. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6069. }
  6070. /** @module AttributeNode **/
  6071. /**
  6072. * Base class for representing shader attributes as nodes.
  6073. *
  6074. * @augments Node
  6075. */
  6076. class AttributeNode extends Node {
  6077. static get type() {
  6078. return 'AttributeNode';
  6079. }
  6080. /**
  6081. * Constructs a new attribute node.
  6082. *
  6083. * @param {String} attributeName - The name of the attribute.
  6084. * @param {String?} nodeType - The node type.
  6085. */
  6086. constructor( attributeName, nodeType = null ) {
  6087. super( nodeType );
  6088. /**
  6089. * `AttributeNode` sets this property to `true` by default.
  6090. *
  6091. * @type {Boolean}
  6092. * @default true
  6093. */
  6094. this.global = true;
  6095. this._attributeName = attributeName;
  6096. }
  6097. getHash( builder ) {
  6098. return this.getAttributeName( builder );
  6099. }
  6100. getNodeType( builder ) {
  6101. let nodeType = this.nodeType;
  6102. if ( nodeType === null ) {
  6103. const attributeName = this.getAttributeName( builder );
  6104. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6105. const attribute = builder.geometry.getAttribute( attributeName );
  6106. nodeType = builder.getTypeFromAttribute( attribute );
  6107. } else {
  6108. nodeType = 'float';
  6109. }
  6110. }
  6111. return nodeType;
  6112. }
  6113. /**
  6114. * Sets the attribute name to the given value. The method can be
  6115. * overwritten in derived classes if the final name must be computed
  6116. * analytically.
  6117. *
  6118. * @param {String} attributeName - The name of the attribute.
  6119. * @return {AttributeNode} A reference to this node.
  6120. */
  6121. setAttributeName( attributeName ) {
  6122. this._attributeName = attributeName;
  6123. return this;
  6124. }
  6125. /**
  6126. * Returns the attribute name of this node. The method can be
  6127. * overwritten in derived classes if the final name must be computed
  6128. * analytically.
  6129. *
  6130. * @param {NodeBuilder} builder - The current node builder.
  6131. * @return {String} The attribute name.
  6132. */
  6133. getAttributeName( /*builder*/ ) {
  6134. return this._attributeName;
  6135. }
  6136. generate( builder ) {
  6137. const attributeName = this.getAttributeName( builder );
  6138. const nodeType = this.getNodeType( builder );
  6139. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6140. if ( geometryAttribute === true ) {
  6141. const attribute = builder.geometry.getAttribute( attributeName );
  6142. const attributeType = builder.getTypeFromAttribute( attribute );
  6143. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6144. if ( builder.shaderStage === 'vertex' ) {
  6145. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6146. } else {
  6147. const nodeVarying = varying( this );
  6148. return nodeVarying.build( builder, nodeType );
  6149. }
  6150. } else {
  6151. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6152. return builder.generateConst( nodeType );
  6153. }
  6154. }
  6155. serialize( data ) {
  6156. super.serialize( data );
  6157. data.global = this.global;
  6158. data._attributeName = this._attributeName;
  6159. }
  6160. deserialize( data ) {
  6161. super.deserialize( data );
  6162. this.global = data.global;
  6163. this._attributeName = data._attributeName;
  6164. }
  6165. }
  6166. /**
  6167. * TSL function for creating an attribute node.
  6168. *
  6169. * @function
  6170. * @param {String} name - The name of the attribute.
  6171. * @param {String?} nodeType - The node type.
  6172. * @returns {AttributeNode}
  6173. */
  6174. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6175. /** @module UV **/
  6176. /**
  6177. * TSL function for creating an uv attribute node with the given index.
  6178. *
  6179. * @function
  6180. * @param {Number} [index=0] - The uv index.
  6181. * @return {AttributeNode<vec2>} The uv attribute node.
  6182. */
  6183. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6184. /** @module TextureSizeNode **/
  6185. /**
  6186. * A node that represents the dimensions of a texture. The texture size is
  6187. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6188. * or `textureSize()`.
  6189. *
  6190. * @augments Node
  6191. */
  6192. class TextureSizeNode extends Node {
  6193. static get type() {
  6194. return 'TextureSizeNode';
  6195. }
  6196. /**
  6197. * Constructs a new texture size node.
  6198. *
  6199. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6200. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6201. */
  6202. constructor( textureNode, levelNode = null ) {
  6203. super( 'uvec2' );
  6204. /**
  6205. * This flag can be used for type testing.
  6206. *
  6207. * @type {Boolean}
  6208. * @readonly
  6209. * @default true
  6210. */
  6211. this.isTextureSizeNode = true;
  6212. /**
  6213. * A texture node which size should be retrieved.
  6214. *
  6215. * @type {TextureNode}
  6216. */
  6217. this.textureNode = textureNode;
  6218. /**
  6219. * A level node which defines the requested mip.
  6220. *
  6221. * @type {Node<int>}
  6222. * @default null
  6223. */
  6224. this.levelNode = levelNode;
  6225. }
  6226. generate( builder, output ) {
  6227. const textureProperty = this.textureNode.build( builder, 'property' );
  6228. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6229. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6230. }
  6231. }
  6232. /**
  6233. * TSL function for creating a texture size node.
  6234. *
  6235. * @function
  6236. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6237. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6238. * @returns {TextureSizeNode}
  6239. */
  6240. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6241. /** @module MatcapUVNode **/
  6242. /**
  6243. * A special type of uniform node that computes the
  6244. * maximum mipmap level for a given texture node.
  6245. *
  6246. * ```js
  6247. * const level = maxMipLevel( textureNode );
  6248. * ```
  6249. *
  6250. * @augments module:UniformNode~UniformNode
  6251. */
  6252. class MaxMipLevelNode extends UniformNode {
  6253. static get type() {
  6254. return 'MaxMipLevelNode';
  6255. }
  6256. /**
  6257. * Constructs a new max mip level node.
  6258. *
  6259. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6260. */
  6261. constructor( textureNode ) {
  6262. super( 0 );
  6263. /**
  6264. * The texture node to compute the max mip level for.
  6265. *
  6266. * @private
  6267. * @type {TextureNode}
  6268. */
  6269. this._textureNode = textureNode;
  6270. /**
  6271. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6272. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6273. *
  6274. * @type {String}
  6275. * @default 'frame'
  6276. */
  6277. this.updateType = NodeUpdateType.FRAME;
  6278. }
  6279. /**
  6280. * The texture node to compute the max mip level for.
  6281. *
  6282. * @readonly
  6283. * @type {TextureNode}
  6284. */
  6285. get textureNode() {
  6286. return this._textureNode;
  6287. }
  6288. /**
  6289. * The texture.
  6290. *
  6291. * @readonly
  6292. * @type {Texture}
  6293. */
  6294. get texture() {
  6295. return this._textureNode.value;
  6296. }
  6297. update() {
  6298. const texture = this.texture;
  6299. const images = texture.images;
  6300. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6301. if ( image && image.width !== undefined ) {
  6302. const { width, height } = image;
  6303. this.value = Math.log2( Math.max( width, height ) );
  6304. }
  6305. }
  6306. }
  6307. /**
  6308. * TSL function for creating a max mip level node.
  6309. *
  6310. * @function
  6311. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6312. * @returns {MaxMipLevelNode}
  6313. */
  6314. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6315. /** @module TextureNode **/
  6316. /**
  6317. * This type of uniform node represents a 2D texture.
  6318. *
  6319. * @augments module:UniformNode~UniformNode
  6320. */
  6321. class TextureNode extends UniformNode {
  6322. static get type() {
  6323. return 'TextureNode';
  6324. }
  6325. /**
  6326. * Constructs a new texture node.
  6327. *
  6328. * @param {Texture} value - The texture.
  6329. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6330. * @param {Node<int>?} [levelNode=null] - The level node.
  6331. * @param {Node<float>?} [biasNode=null] - The bias node.
  6332. */
  6333. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6334. super( value );
  6335. /**
  6336. * This flag can be used for type testing.
  6337. *
  6338. * @type {Boolean}
  6339. * @readonly
  6340. * @default true
  6341. */
  6342. this.isTextureNode = true;
  6343. /**
  6344. * Represents the texture coordinates.
  6345. *
  6346. * @type {Node<vec2|vec3>?}
  6347. * @default null
  6348. */
  6349. this.uvNode = uvNode;
  6350. /**
  6351. * Represents the mip level that should be selected.
  6352. *
  6353. * @type {Node<int>?}
  6354. * @default null
  6355. */
  6356. this.levelNode = levelNode;
  6357. /**
  6358. * Represents the bias to be applied during level-of-detail computation.
  6359. *
  6360. * @type {Node<float>?}
  6361. * @default null
  6362. */
  6363. this.biasNode = biasNode;
  6364. /**
  6365. * Represents a reference value a texture sample is compared to.
  6366. *
  6367. * @type {Node<float>?}
  6368. * @default null
  6369. */
  6370. this.compareNode = null;
  6371. /**
  6372. * When using texture arrays, the depth node defines the layer to select.
  6373. *
  6374. * @type {Node<int>?}
  6375. * @default null
  6376. */
  6377. this.depthNode = null;
  6378. /**
  6379. * When defined, a texture is sampled using explicit gradients.
  6380. *
  6381. * @type {Array<Node<vec2>>?}
  6382. * @default null
  6383. */
  6384. this.gradNode = null;
  6385. /**
  6386. * Whether texture values should be sampled or fetched.
  6387. *
  6388. * @type {Boolean}
  6389. * @default true
  6390. */
  6391. this.sampler = true;
  6392. /**
  6393. * Whether the uv transformation matrix should be
  6394. * automatically updated or not. Use `setUpdateMatrix()`
  6395. * if you want to change the value of the property.
  6396. *
  6397. * @type {Boolean}
  6398. * @default false
  6399. */
  6400. this.updateMatrix = false;
  6401. /**
  6402. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6403. * sets the value to `frame` when the uv transformation matrix should
  6404. * automatically be updated.
  6405. *
  6406. * @type {String}
  6407. * @default 'none'
  6408. */
  6409. this.updateType = NodeUpdateType.NONE;
  6410. /**
  6411. * The reference node.
  6412. *
  6413. * @type {Node?}
  6414. * @default null
  6415. */
  6416. this.referenceNode = null;
  6417. /**
  6418. * The texture value is stored in a private property.
  6419. *
  6420. * @private
  6421. * @type {Texture}
  6422. */
  6423. this._value = value;
  6424. /**
  6425. * The uniform node that represents the uv transformation matrix.
  6426. *
  6427. * @private
  6428. * @type {UniformNode<mat3>?}
  6429. */
  6430. this._matrixUniform = null;
  6431. this.setUpdateMatrix( uvNode === null );
  6432. }
  6433. set value( value ) {
  6434. if ( this.referenceNode ) {
  6435. this.referenceNode.value = value;
  6436. } else {
  6437. this._value = value;
  6438. }
  6439. }
  6440. /**
  6441. * The texture value.
  6442. *
  6443. * @type {Texture}
  6444. */
  6445. get value() {
  6446. return this.referenceNode ? this.referenceNode.value : this._value;
  6447. }
  6448. /**
  6449. * Overwritten since the uniform hash is defined by the texture's UUID.
  6450. *
  6451. * @param {NodeBuilder} builder - The current node builder.
  6452. * @return {String} The uniform hash.
  6453. */
  6454. getUniformHash( /*builder*/ ) {
  6455. return this.value.uuid;
  6456. }
  6457. /**
  6458. * Overwritten since the node type is inferred from the texture type.
  6459. *
  6460. * @param {NodeBuilder} builder - The current node builder.
  6461. * @return {String} The node type.
  6462. */
  6463. getNodeType( /*builder*/ ) {
  6464. if ( this.value.isDepthTexture === true ) return 'float';
  6465. if ( this.value.type === UnsignedIntType ) {
  6466. return 'uvec4';
  6467. } else if ( this.value.type === IntType ) {
  6468. return 'ivec4';
  6469. }
  6470. return 'vec4';
  6471. }
  6472. /**
  6473. * Overwrites the default implementation to return a fixed value `'texture'`.
  6474. *
  6475. * @param {NodeBuilder} builder - The current node builder.
  6476. * @return {String} The input type.
  6477. */
  6478. getInputType( /*builder*/ ) {
  6479. return 'texture';
  6480. }
  6481. /**
  6482. * Returns a default uvs based on the current texture's channel.
  6483. *
  6484. * @return {AttributeNode<vec2>} The default uvs.
  6485. */
  6486. getDefaultUV() {
  6487. return uv( this.value.channel );
  6488. }
  6489. /**
  6490. * Overwritten to always return the texture reference of the node.
  6491. *
  6492. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6493. * @return {Texture} The texture reference.
  6494. */
  6495. updateReference( /*state*/ ) {
  6496. return this.value;
  6497. }
  6498. /**
  6499. * Transforms the given uv node with the texture transformation matrix.
  6500. *
  6501. * @param {Node} uvNode - The uv node to transform.
  6502. * @return {Node} The transformed uv node.
  6503. */
  6504. getTransformedUV( uvNode ) {
  6505. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6506. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6507. }
  6508. /**
  6509. * Defines whether the uv transformation matrix should automatically be updated or not.
  6510. *
  6511. * @param {Boolean} value - The update toggle.
  6512. * @return {TextureNode} A reference to this node.
  6513. */
  6514. setUpdateMatrix( value ) {
  6515. this.updateMatrix = value;
  6516. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6517. return this;
  6518. }
  6519. /**
  6520. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6521. * to modify the uv node for correct sampling.
  6522. *
  6523. * @param {NodeBuilder} builder - The current node builder.
  6524. * @param {Node} uvNode - The uv node to setup.
  6525. * @return {Node} The updated uv node.
  6526. */
  6527. setupUV( builder, uvNode ) {
  6528. const texture = this.value;
  6529. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6530. if ( this.sampler ) {
  6531. uvNode = uvNode.flipY();
  6532. } else {
  6533. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6534. }
  6535. }
  6536. return uvNode;
  6537. }
  6538. /**
  6539. * Setups texture node by preparing the internal nodes for code generation.
  6540. *
  6541. * @param {NodeBuilder} builder - The current node builder.
  6542. */
  6543. setup( builder ) {
  6544. const properties = builder.getNodeProperties( this );
  6545. properties.referenceNode = this.referenceNode;
  6546. //
  6547. const texture = this.value;
  6548. if ( ! texture || texture.isTexture !== true ) {
  6549. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6550. }
  6551. //
  6552. let uvNode = this.uvNode;
  6553. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6554. uvNode = builder.context.getUV( this );
  6555. }
  6556. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6557. if ( this.updateMatrix === true ) {
  6558. uvNode = this.getTransformedUV( uvNode );
  6559. }
  6560. uvNode = this.setupUV( builder, uvNode );
  6561. //
  6562. let levelNode = this.levelNode;
  6563. if ( levelNode === null && builder.context.getTextureLevel ) {
  6564. levelNode = builder.context.getTextureLevel( this );
  6565. }
  6566. //
  6567. properties.uvNode = uvNode;
  6568. properties.levelNode = levelNode;
  6569. properties.biasNode = this.biasNode;
  6570. properties.compareNode = this.compareNode;
  6571. properties.gradNode = this.gradNode;
  6572. properties.depthNode = this.depthNode;
  6573. }
  6574. /**
  6575. * Generates the uv code snippet.
  6576. *
  6577. * @param {NodeBuilder} builder - The current node builder.
  6578. * @param {Node} uvNode - The uv node to generate code for.
  6579. * @return {String} The generated code snippet.
  6580. */
  6581. generateUV( builder, uvNode ) {
  6582. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6583. }
  6584. /**
  6585. * Generates the snippet for the texture sampling.
  6586. *
  6587. * @param {NodeBuilder} builder - The current node builder.
  6588. * @param {String} textureProperty - The texture property.
  6589. * @param {String} uvSnippet - The uv snippet.
  6590. * @param {String?} levelSnippet - The level snippet.
  6591. * @param {String?} biasSnippet - The bias snippet.
  6592. * @param {String?} depthSnippet - The depth snippet.
  6593. * @param {String?} compareSnippet - The compare snippet.
  6594. * @param {Array<String>?} gradSnippet - The grad snippet.
  6595. * @return {String} The generated code snippet.
  6596. */
  6597. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6598. const texture = this.value;
  6599. let snippet;
  6600. if ( levelSnippet ) {
  6601. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6602. } else if ( biasSnippet ) {
  6603. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6604. } else if ( gradSnippet ) {
  6605. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6606. } else if ( compareSnippet ) {
  6607. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6608. } else if ( this.sampler === false ) {
  6609. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6610. } else {
  6611. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6612. }
  6613. return snippet;
  6614. }
  6615. /**
  6616. * Generates the code snippet of the texture node.
  6617. *
  6618. * @param {NodeBuilder} builder - The current node builder.
  6619. * @param {String} output - The current output.
  6620. * @return {String} The generated code snippet.
  6621. */
  6622. generate( builder, output ) {
  6623. const texture = this.value;
  6624. const properties = builder.getNodeProperties( this );
  6625. const textureProperty = super.generate( builder, 'property' );
  6626. if ( output === 'sampler' ) {
  6627. return textureProperty + '_sampler';
  6628. } else if ( builder.isReference( output ) ) {
  6629. return textureProperty;
  6630. } else {
  6631. const nodeData = builder.getDataFromNode( this );
  6632. let propertyName = nodeData.propertyName;
  6633. if ( propertyName === undefined ) {
  6634. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6635. const uvSnippet = this.generateUV( builder, uvNode );
  6636. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6637. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6638. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6639. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6640. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6641. const nodeVar = builder.getVarFromNode( this );
  6642. propertyName = builder.getPropertyName( nodeVar );
  6643. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6644. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6645. nodeData.snippet = snippet;
  6646. nodeData.propertyName = propertyName;
  6647. }
  6648. let snippet = propertyName;
  6649. const nodeType = this.getNodeType( builder );
  6650. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6651. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6652. }
  6653. return builder.format( snippet, nodeType, output );
  6654. }
  6655. }
  6656. /**
  6657. * Sets the sampler value.
  6658. *
  6659. * @param {Boolean} value - The sampler value to set.
  6660. * @return {TextureNode} A reference to this texture node.
  6661. */
  6662. setSampler( value ) {
  6663. this.sampler = value;
  6664. return this;
  6665. }
  6666. /**
  6667. * Returns the sampler value.
  6668. *
  6669. * @return {Boolean} The sampler value.
  6670. */
  6671. getSampler() {
  6672. return this.sampler;
  6673. }
  6674. // @TODO: Move to TSL
  6675. /**
  6676. * @function
  6677. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6678. *
  6679. * @param {Node} uvNode - The uv node.
  6680. * @return {TextureNode} A texture node representing the texture sample.
  6681. */
  6682. uv( uvNode ) { // @deprecated, r172
  6683. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6684. return this.sample( uvNode );
  6685. }
  6686. /**
  6687. * Samples the texture with the given uv node.
  6688. *
  6689. * @param {Node} uvNode - The uv node.
  6690. * @return {TextureNode} A texture node representing the texture sample.
  6691. */
  6692. sample( uvNode ) {
  6693. const textureNode = this.clone();
  6694. textureNode.uvNode = nodeObject( uvNode );
  6695. textureNode.referenceNode = this.getSelf();
  6696. return nodeObject( textureNode );
  6697. }
  6698. /**
  6699. * Samples a blurred version of the texture by defining an internal bias.
  6700. *
  6701. * @param {Node<float>} amountNode - How blurred the texture should be.
  6702. * @return {TextureNode} A texture node representing the texture sample.
  6703. */
  6704. blur( amountNode ) {
  6705. const textureNode = this.clone();
  6706. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6707. textureNode.referenceNode = this.getSelf();
  6708. return nodeObject( textureNode );
  6709. }
  6710. /**
  6711. * Samples a specific mip of the texture.
  6712. *
  6713. * @param {Node<int>} levelNode - The mip level to sample.
  6714. * @return {TextureNode} A texture node representing the texture sample.
  6715. */
  6716. level( levelNode ) {
  6717. const textureNode = this.clone();
  6718. textureNode.levelNode = nodeObject( levelNode );
  6719. textureNode.referenceNode = this.getSelf();
  6720. return nodeObject( textureNode );
  6721. }
  6722. /**
  6723. * Returns the texture size of the requested level.
  6724. *
  6725. * @param {Node<int>} levelNode - The level to compute the size for.
  6726. * @return {TextureSizeNode} The texture size.
  6727. */
  6728. size( levelNode ) {
  6729. return textureSize( this, levelNode );
  6730. }
  6731. /**
  6732. * Samples the texture with the given bias.
  6733. *
  6734. * @param {Node<float>} biasNode - The bias node.
  6735. * @return {TextureNode} A texture node representing the texture sample.
  6736. */
  6737. bias( biasNode ) {
  6738. const textureNode = this.clone();
  6739. textureNode.biasNode = nodeObject( biasNode );
  6740. textureNode.referenceNode = this.getSelf();
  6741. return nodeObject( textureNode );
  6742. }
  6743. /**
  6744. * Samples the texture by executing a compare operation.
  6745. *
  6746. * @param {Node<float>} compareNode - The node that defines the compare value.
  6747. * @return {TextureNode} A texture node representing the texture sample.
  6748. */
  6749. compare( compareNode ) {
  6750. const textureNode = this.clone();
  6751. textureNode.compareNode = nodeObject( compareNode );
  6752. textureNode.referenceNode = this.getSelf();
  6753. return nodeObject( textureNode );
  6754. }
  6755. /**
  6756. * Samples the texture using an explicit gradient.
  6757. *
  6758. * @param {Node<vec2>} gradNodeX - The gradX node.
  6759. * @param {Node<vec2>} gradNodeY - The gradY node.
  6760. * @return {TextureNode} A texture node representing the texture sample.
  6761. */
  6762. grad( gradNodeX, gradNodeY ) {
  6763. const textureNode = this.clone();
  6764. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6765. textureNode.referenceNode = this.getSelf();
  6766. return nodeObject( textureNode );
  6767. }
  6768. /**
  6769. * Samples the texture by defining a depth node.
  6770. *
  6771. * @param {Node<int>} depthNode - The depth node.
  6772. * @return {TextureNode} A texture node representing the texture sample.
  6773. */
  6774. depth( depthNode ) {
  6775. const textureNode = this.clone();
  6776. textureNode.depthNode = nodeObject( depthNode );
  6777. textureNode.referenceNode = this.getSelf();
  6778. return nodeObject( textureNode );
  6779. }
  6780. // --
  6781. serialize( data ) {
  6782. super.serialize( data );
  6783. data.value = this.value.toJSON( data.meta ).uuid;
  6784. data.sampler = this.sampler;
  6785. data.updateMatrix = this.updateMatrix;
  6786. data.updateType = this.updateType;
  6787. }
  6788. deserialize( data ) {
  6789. super.deserialize( data );
  6790. this.value = data.meta.textures[ data.value ];
  6791. this.sampler = data.sampler;
  6792. this.updateMatrix = data.updateMatrix;
  6793. this.updateType = data.updateType;
  6794. }
  6795. /**
  6796. * The update is used to implement the update of the uv transformation matrix.
  6797. */
  6798. update() {
  6799. const texture = this.value;
  6800. const matrixUniform = this._matrixUniform;
  6801. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6802. if ( texture.matrixAutoUpdate === true ) {
  6803. texture.updateMatrix();
  6804. }
  6805. }
  6806. /**
  6807. * Clones the texture node.
  6808. *
  6809. * @return {TextureNode} The cloned texture node.
  6810. */
  6811. clone() {
  6812. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6813. newNode.sampler = this.sampler;
  6814. return newNode;
  6815. }
  6816. }
  6817. /**
  6818. * TSL function for creating a texture node.
  6819. *
  6820. * @function
  6821. * @param {Texture} value - The texture.
  6822. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6823. * @param {Node<int>?} [levelNode=null] - The level node.
  6824. * @param {Node<float>?} [biasNode=null] - The bias node.
  6825. * @returns {TextureNode}
  6826. */
  6827. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6828. /**
  6829. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6830. *
  6831. * @function
  6832. * @param {Texture} value - The texture.
  6833. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6834. * @param {Node<int>?} [levelNode=null] - The level node.
  6835. * @param {Node<float>?} [biasNode=null] - The bias node.
  6836. * @returns {TextureNode}
  6837. */
  6838. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6839. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6840. /**
  6841. * Converts a texture or texture node to a sampler.
  6842. *
  6843. * @function
  6844. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6845. * @returns {Node}
  6846. */
  6847. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6848. /** @module BufferNode **/
  6849. /**
  6850. * A special type of uniform node which represents array-like data
  6851. * as uniform buffers. The access usually happens via `element()`
  6852. * which returns an instance of {@link ArrayElementNode}. For example:
  6853. *
  6854. * ```js
  6855. * const bufferNode = buffer( array, 'mat4', count );
  6856. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  6857. * ```
  6858. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  6859. * since it handles more input types and automatically cares about buffer paddings.
  6860. *
  6861. * @augments module:UniformNode~UniformNode
  6862. */
  6863. class BufferNode extends UniformNode {
  6864. static get type() {
  6865. return 'BufferNode';
  6866. }
  6867. /**
  6868. * Constructs a new buffer node.
  6869. *
  6870. * @param {Array<Number>} value - Array-like buffer data.
  6871. * @param {String} bufferType - The data type of the buffer.
  6872. * @param {Number} [bufferCount=0] - The count of buffer elements.
  6873. */
  6874. constructor( value, bufferType, bufferCount = 0 ) {
  6875. super( value, bufferType );
  6876. /**
  6877. * This flag can be used for type testing.
  6878. *
  6879. * @type {Boolean}
  6880. * @readonly
  6881. * @default true
  6882. */
  6883. this.isBufferNode = true;
  6884. /**
  6885. * The data type of the buffer.
  6886. *
  6887. * @type {String}
  6888. */
  6889. this.bufferType = bufferType;
  6890. /**
  6891. * The uniform node that holds the value of the reference node.
  6892. *
  6893. * @type {Number}
  6894. * @default 0
  6895. */
  6896. this.bufferCount = bufferCount;
  6897. }
  6898. /**
  6899. * The data type of the buffer elements.
  6900. *
  6901. * @param {NodeBuilder} builder - The current node builder.
  6902. * @return {String} The element type.
  6903. */
  6904. getElementType( builder ) {
  6905. return this.getNodeType( builder );
  6906. }
  6907. /**
  6908. * Overwrites the default implementation to return a fixed value `'buffer'`.
  6909. *
  6910. * @param {NodeBuilder} builder - The current node builder.
  6911. * @return {String} The input type.
  6912. */
  6913. getInputType( /*builder*/ ) {
  6914. return 'buffer';
  6915. }
  6916. }
  6917. /**
  6918. * TSL function for creating a buffer node.
  6919. *
  6920. * @function
  6921. * @param {Array} value - Array-like buffer data.
  6922. * @param {String} type - The data type of a buffer element.
  6923. * @param {Number} count - The count of buffer elements.
  6924. * @returns {BufferNode}
  6925. */
  6926. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  6927. /** @module UniformArrayNode **/
  6928. /**
  6929. * Represents the element access on uniform array nodes.
  6930. *
  6931. * @augments ArrayElementNode
  6932. */
  6933. class UniformArrayElementNode extends ArrayElementNode {
  6934. static get type() {
  6935. return 'UniformArrayElementNode';
  6936. }
  6937. /**
  6938. * Constructs a new buffer node.
  6939. *
  6940. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  6941. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  6942. */
  6943. constructor( uniformArrayNode, indexNode ) {
  6944. super( uniformArrayNode, indexNode );
  6945. /**
  6946. * This flag can be used for type testing.
  6947. *
  6948. * @type {Boolean}
  6949. * @readonly
  6950. * @default true
  6951. */
  6952. this.isArrayBufferElementNode = true;
  6953. }
  6954. generate( builder ) {
  6955. const snippet = super.generate( builder );
  6956. const type = this.getNodeType();
  6957. const paddedType = this.node.getPaddedType();
  6958. return builder.format( snippet, paddedType, type );
  6959. }
  6960. }
  6961. /**
  6962. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  6963. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  6964. * data types in the array (e.g `three.js` primitives) and automatically
  6965. * manage buffer padding. It should be the first choice when working with
  6966. * uniforms buffers.
  6967. * ```js
  6968. * const tintColors = uniformArray( [
  6969. * new Color( 1, 0, 0 ),
  6970. * new Color( 0, 1, 0 ),
  6971. * new Color( 0, 0, 1 )
  6972. * ], 'color' );
  6973. *
  6974. * const redColor = tintColors.element( 0 );
  6975. *
  6976. * @augments module:BufferNode~BufferNode
  6977. */
  6978. class UniformArrayNode extends BufferNode {
  6979. static get type() {
  6980. return 'UniformArrayNode';
  6981. }
  6982. /**
  6983. * Constructs a new uniform array node.
  6984. *
  6985. * @param {Array<Any>} value - Array holding the buffer data.
  6986. * @param {String?} [elementType=null] - The data type of a buffer element.
  6987. */
  6988. constructor( value, elementType = null ) {
  6989. super( null );
  6990. /**
  6991. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  6992. * hold number primitives as well as three.js objects like vectors, matrices
  6993. * or colors.
  6994. *
  6995. * @type {Array<Any>}
  6996. */
  6997. this.array = value;
  6998. /**
  6999. * The data type of an array element.
  7000. *
  7001. * @type {String}
  7002. */
  7003. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7004. /**
  7005. * The padded type. Uniform buffers must conform to a certain buffer layout
  7006. * so a separate type is computed to ensure correct buffer size.
  7007. *
  7008. * @type {String}
  7009. */
  7010. this.paddedType = this.getPaddedType();
  7011. /**
  7012. * Overwritten since uniform array nodes are updated per render.
  7013. *
  7014. * @type {String}
  7015. * @default 'render'
  7016. */
  7017. this.updateType = NodeUpdateType.RENDER;
  7018. /**
  7019. * This flag can be used for type testing.
  7020. *
  7021. * @type {Boolean}
  7022. * @readonly
  7023. * @default true
  7024. */
  7025. this.isArrayBufferNode = true;
  7026. }
  7027. /**
  7028. * This method is overwritten since the node type is inferred from the
  7029. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7030. *
  7031. * @param {NodeBuilder} builder - The current node builder.
  7032. * @return {String} The node type.
  7033. */
  7034. getNodeType( /*builder*/ ) {
  7035. return this.paddedType;
  7036. }
  7037. /**
  7038. * The data type of the array elements.
  7039. *
  7040. * @param {NodeBuilder} builder - The current node builder.
  7041. * @return {String} The element type.
  7042. */
  7043. getElementType() {
  7044. return this.elementType;
  7045. }
  7046. /**
  7047. * Returns the padded type based on the element type.
  7048. *
  7049. * @return {String} The padded type.
  7050. */
  7051. getPaddedType() {
  7052. const elementType = this.elementType;
  7053. let paddedType = 'vec4';
  7054. if ( elementType === 'mat2' ) {
  7055. paddedType = 'mat2';
  7056. } else if ( /mat/.test( elementType ) === true ) {
  7057. paddedType = 'mat4';
  7058. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7059. paddedType = 'ivec4';
  7060. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7061. paddedType = 'uvec4';
  7062. }
  7063. return paddedType;
  7064. }
  7065. /**
  7066. * The update makes sure to correctly transfer the data from the (complex) objects
  7067. * in the array to the internal, correctly padded value buffer.
  7068. *
  7069. * @param {NodeFrame} frame - A reference to the current node frame.
  7070. */
  7071. update( /*frame*/ ) {
  7072. const { array, value } = this;
  7073. const elementType = this.elementType;
  7074. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7075. for ( let i = 0; i < array.length; i ++ ) {
  7076. const index = i * 4;
  7077. value[ index ] = array[ i ];
  7078. }
  7079. } else if ( elementType === 'color' ) {
  7080. for ( let i = 0; i < array.length; i ++ ) {
  7081. const index = i * 4;
  7082. const vector = array[ i ];
  7083. value[ index ] = vector.r;
  7084. value[ index + 1 ] = vector.g;
  7085. value[ index + 2 ] = vector.b || 0;
  7086. //value[ index + 3 ] = vector.a || 0;
  7087. }
  7088. } else if ( elementType === 'mat2' ) {
  7089. for ( let i = 0; i < array.length; i ++ ) {
  7090. const index = i * 4;
  7091. const matrix = array[ i ];
  7092. value[ index ] = matrix.elements[ 0 ];
  7093. value[ index + 1 ] = matrix.elements[ 1 ];
  7094. value[ index + 2 ] = matrix.elements[ 2 ];
  7095. value[ index + 3 ] = matrix.elements[ 3 ];
  7096. }
  7097. } else if ( elementType === 'mat3' ) {
  7098. for ( let i = 0; i < array.length; i ++ ) {
  7099. const index = i * 16;
  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 + 4 ] = matrix.elements[ 3 ];
  7105. value[ index + 5 ] = matrix.elements[ 4 ];
  7106. value[ index + 6 ] = matrix.elements[ 5 ];
  7107. value[ index + 8 ] = matrix.elements[ 6 ];
  7108. value[ index + 9 ] = matrix.elements[ 7 ];
  7109. value[ index + 10 ] = matrix.elements[ 8 ];
  7110. value[ index + 15 ] = 1;
  7111. }
  7112. } else if ( elementType === 'mat4' ) {
  7113. for ( let i = 0; i < array.length; i ++ ) {
  7114. const index = i * 16;
  7115. const matrix = array[ i ];
  7116. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7117. value[ index + i ] = matrix.elements[ i ];
  7118. }
  7119. }
  7120. } else {
  7121. for ( let i = 0; i < array.length; i ++ ) {
  7122. const index = i * 4;
  7123. const vector = array[ i ];
  7124. value[ index ] = vector.x;
  7125. value[ index + 1 ] = vector.y;
  7126. value[ index + 2 ] = vector.z || 0;
  7127. value[ index + 3 ] = vector.w || 0;
  7128. }
  7129. }
  7130. }
  7131. /**
  7132. * Implement the value buffer creation based on the array data.
  7133. *
  7134. * @param {NodeBuilder} builder - A reference to the current node builder.
  7135. * @return {null}
  7136. */
  7137. setup( builder ) {
  7138. const length = this.array.length;
  7139. const elementType = this.elementType;
  7140. let arrayType = Float32Array;
  7141. const paddedType = this.paddedType;
  7142. const paddedElementLength = builder.getTypeLength( paddedType );
  7143. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7144. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7145. this.value = new arrayType( length * paddedElementLength );
  7146. this.bufferCount = length;
  7147. this.bufferType = paddedType;
  7148. return super.setup( builder );
  7149. }
  7150. /**
  7151. * Overwrites the default `element()` method to provide element access
  7152. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7153. *
  7154. * @param {IndexNode} indexNode - The index node.
  7155. * @return {UniformArrayElementNode}
  7156. */
  7157. element( indexNode ) {
  7158. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7159. }
  7160. }
  7161. /**
  7162. * TSL function for creating an uniform array node.
  7163. *
  7164. * @function
  7165. * @param {Array<Any>} values - Array-like data.
  7166. * @param {String?} nodeType - The data type of the array elements.
  7167. * @returns {UniformArrayNode}
  7168. */
  7169. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7170. /**
  7171. * @function
  7172. * @deprecated since r168. Use {@link uniformArray} instead.
  7173. *
  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 uniforms = ( values, nodeType ) => { // @deprecated, r168
  7179. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7180. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7181. };
  7182. /** @module Camera **/
  7183. /**
  7184. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7185. *
  7186. * @type {UniformNode<uint>}
  7187. */
  7188. const cameraIndex = /*@__PURE__*/ uniform( 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).vertexStage();
  7189. /**
  7190. * TSL object that represents the `near` value of the camera used for the current render.
  7191. *
  7192. * @type {UniformNode<float>}
  7193. */
  7194. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7195. /**
  7196. * TSL object that represents the `far` value of the camera used for the current render.
  7197. *
  7198. * @type {UniformNode<float>}
  7199. */
  7200. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7201. /**
  7202. * TSL object that represents the projection matrix of the camera used for the current render.
  7203. *
  7204. * @type {UniformNode<mat4>}
  7205. */
  7206. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7207. let cameraProjectionMatrix;
  7208. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7209. const matrices = [];
  7210. for ( const subCamera of camera.cameras ) {
  7211. matrices.push( subCamera.projectionMatrix );
  7212. }
  7213. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7214. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7215. } else {
  7216. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7217. }
  7218. return cameraProjectionMatrix;
  7219. } ).once() )();
  7220. /**
  7221. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7222. *
  7223. * @type {UniformNode<mat4>}
  7224. */
  7225. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7226. /**
  7227. * TSL object that represents the view matrix of the camera used for the current render.
  7228. *
  7229. * @type {UniformNode<mat4>}
  7230. */
  7231. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7232. let cameraViewMatrix;
  7233. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7234. const matrices = [];
  7235. for ( const subCamera of camera.cameras ) {
  7236. matrices.push( subCamera.matrixWorldInverse );
  7237. }
  7238. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7239. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7240. } else {
  7241. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7242. }
  7243. return cameraViewMatrix;
  7244. } ).once() )();
  7245. /**
  7246. * TSL object that represents the world matrix of the camera used for the current render.
  7247. *
  7248. * @type {UniformNode<mat4>}
  7249. */
  7250. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7251. /**
  7252. * TSL object that represents the normal matrix of the camera used for the current render.
  7253. *
  7254. * @type {UniformNode<mat3>}
  7255. */
  7256. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7257. /**
  7258. * TSL object that represents the position in world space of the camera used for the current render.
  7259. *
  7260. * @type {UniformNode<vec3>}
  7261. */
  7262. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7263. /** @module Object3DNode **/
  7264. /**
  7265. * This node can be used to access transformation related metrics of 3D objects.
  7266. * Depending on the selected scope, a different metric is represented as a uniform
  7267. * in the shader. The following scopes are supported:
  7268. *
  7269. * - `POSITION`: The object's position in world space.
  7270. * - `VIEW_POSITION`: The object's position in view/camera space.
  7271. * - `DIRECTION`: The object's direction in world space.
  7272. * - `SCALE`: The object's scale in world space.
  7273. * - `WORLD_MATRIX`: The object's matrix in world space.
  7274. *
  7275. * @augments Node
  7276. */
  7277. class Object3DNode extends Node {
  7278. static get type() {
  7279. return 'Object3DNode';
  7280. }
  7281. /**
  7282. * Constructs a new object 3D node.
  7283. *
  7284. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7285. * @param {Object3D?} [object3d=null] - The 3D object.
  7286. */
  7287. constructor( scope, object3d = null ) {
  7288. super();
  7289. /**
  7290. * The node reports a different type of transformation depending on the scope.
  7291. *
  7292. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7293. */
  7294. this.scope = scope;
  7295. /**
  7296. * The 3D object.
  7297. *
  7298. * @type {Object3D?}
  7299. * @default null
  7300. */
  7301. this.object3d = object3d;
  7302. /**
  7303. * Overwritten since this type of node is updated per object.
  7304. *
  7305. * @type {String}
  7306. * @default 'object'
  7307. */
  7308. this.updateType = NodeUpdateType.OBJECT;
  7309. /**
  7310. * Holds the value of the node as a uniform.
  7311. *
  7312. * @private
  7313. * @type {UniformNode}
  7314. */
  7315. this._uniformNode = new UniformNode( null );
  7316. }
  7317. /**
  7318. * Overwritten since the node type is inferred from the scope.
  7319. *
  7320. * @return {String} The node type.
  7321. */
  7322. getNodeType() {
  7323. const scope = this.scope;
  7324. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7325. return 'mat4';
  7326. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7327. return 'vec3';
  7328. }
  7329. }
  7330. /**
  7331. * Updates the uniform value depending on the scope.
  7332. *
  7333. * @param {NodeFrame} frame - The current node frame.
  7334. */
  7335. update( frame ) {
  7336. const object = this.object3d;
  7337. const uniformNode = this._uniformNode;
  7338. const scope = this.scope;
  7339. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7340. uniformNode.value = object.matrixWorld;
  7341. } else if ( scope === Object3DNode.POSITION ) {
  7342. uniformNode.value = uniformNode.value || new Vector3();
  7343. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7344. } else if ( scope === Object3DNode.SCALE ) {
  7345. uniformNode.value = uniformNode.value || new Vector3();
  7346. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7347. } else if ( scope === Object3DNode.DIRECTION ) {
  7348. uniformNode.value = uniformNode.value || new Vector3();
  7349. object.getWorldDirection( uniformNode.value );
  7350. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7351. const camera = frame.camera;
  7352. uniformNode.value = uniformNode.value || new Vector3();
  7353. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7354. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7355. }
  7356. }
  7357. /**
  7358. * Generates the code snippet of the uniform node. The node type of the uniform
  7359. * node also depends on the selected scope.
  7360. *
  7361. * @param {NodeBuilder} builder - The current node builder.
  7362. * @return {String} The generated code snippet.
  7363. */
  7364. generate( builder ) {
  7365. const scope = this.scope;
  7366. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7367. this._uniformNode.nodeType = 'mat4';
  7368. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7369. this._uniformNode.nodeType = 'vec3';
  7370. }
  7371. return this._uniformNode.build( builder );
  7372. }
  7373. serialize( data ) {
  7374. super.serialize( data );
  7375. data.scope = this.scope;
  7376. }
  7377. deserialize( data ) {
  7378. super.deserialize( data );
  7379. this.scope = data.scope;
  7380. }
  7381. }
  7382. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7383. Object3DNode.POSITION = 'position';
  7384. Object3DNode.SCALE = 'scale';
  7385. Object3DNode.VIEW_POSITION = 'viewPosition';
  7386. Object3DNode.DIRECTION = 'direction';
  7387. /**
  7388. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7389. *
  7390. * @function
  7391. * @param {Object3D?} [object3d=null] - The 3D object.
  7392. * @returns {Object3DNode<vec3>}
  7393. */
  7394. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7395. /**
  7396. * TSL function for creating an object 3D node that represents the object's world matrix.
  7397. *
  7398. * @function
  7399. * @param {Object3D?} [object3d=null] - The 3D object.
  7400. * @returns {Object3DNode<mat4>}
  7401. */
  7402. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7403. /**
  7404. * TSL function for creating an object 3D node that represents the object's position in world space.
  7405. *
  7406. * @function
  7407. * @param {Object3D?} [object3d=null] - The 3D object.
  7408. * @returns {Object3DNode<vec3>}
  7409. */
  7410. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7411. /**
  7412. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7413. *
  7414. * @function
  7415. * @param {Object3D?} [object3d=null] - The 3D object.
  7416. * @returns {Object3DNode<vec3>}
  7417. */
  7418. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7419. /**
  7420. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7421. *
  7422. * @function
  7423. * @param {Object3D?} [object3d=null] - The 3D object.
  7424. * @returns {Object3DNode<vec3>}
  7425. */
  7426. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7427. /** @module ModelNode **/
  7428. /**
  7429. * This type of node is a specialized version of `Object3DNode`
  7430. * with larger set of model related metrics. Unlike `Object3DNode`,
  7431. * `ModelNode` extracts the reference to the 3D object from the
  7432. * current node frame state.
  7433. *
  7434. * @augments module:Object3DNode~Object3DNode
  7435. */
  7436. class ModelNode extends Object3DNode {
  7437. static get type() {
  7438. return 'ModelNode';
  7439. }
  7440. /**
  7441. * Constructs a new object model node.
  7442. *
  7443. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7444. */
  7445. constructor( scope ) {
  7446. super( scope );
  7447. }
  7448. /**
  7449. * Extracts the model reference from the frame state and then
  7450. * updates the uniform value depending on the scope.
  7451. *
  7452. * @param {NodeFrame} frame - The current node frame.
  7453. */
  7454. update( frame ) {
  7455. this.object3d = frame.object;
  7456. super.update( frame );
  7457. }
  7458. }
  7459. /**
  7460. * TSL object that represents the object's direction in world space.
  7461. *
  7462. * @type {ModelNode<vec3>}
  7463. */
  7464. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7465. /**
  7466. * TSL object that represents the object's world matrix.
  7467. *
  7468. * @type {ModelNode<mat4>}
  7469. */
  7470. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7471. /**
  7472. * TSL object that represents the object's position in world space.
  7473. *
  7474. * @type {ModelNode<vec3>}
  7475. */
  7476. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7477. /**
  7478. * TSL object that represents the object's scale in world space.
  7479. *
  7480. * @type {ModelNode<vec3>}
  7481. */
  7482. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7483. /**
  7484. * TSL object that represents the object's position in view/camera space.
  7485. *
  7486. * @type {ModelNode<vec3>}
  7487. */
  7488. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7489. /**
  7490. * TSL object that represents the object's normal matrix.
  7491. *
  7492. * @type {UniformNode<mat3>}
  7493. */
  7494. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7495. /**
  7496. * TSL object that represents the object's inverse world matrix.
  7497. *
  7498. * @type {UniformNode<mat4>}
  7499. */
  7500. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7501. /**
  7502. * TSL object that represents the object's model view matrix.
  7503. *
  7504. * @type {Node<mat4>}
  7505. */
  7506. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7507. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7508. } ).once() )().toVar( 'modelViewMatrix' );
  7509. // GPU Precision
  7510. /**
  7511. * TSL object that represents the object's model view in `mediump` precision.
  7512. *
  7513. * @type {Node<mat4>}
  7514. */
  7515. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7516. // CPU Precision
  7517. /**
  7518. * TSL object that represents the object's model view in `highp` precision
  7519. * which is achieved by computing the matrix in JS and not in the shader.
  7520. *
  7521. * @type {Node<mat4>}
  7522. */
  7523. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7524. builder.context.isHighPrecisionModelViewMatrix = true;
  7525. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7526. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7527. } );
  7528. } ).once() )().toVar( 'highpModelViewMatrix' );
  7529. /**
  7530. * TSL object that represents the object's model normal view in `highp` precision
  7531. * which is achieved by computing the matrix in JS and not in the shader.
  7532. *
  7533. * @type {Node<mat3>}
  7534. */
  7535. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7536. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7537. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7538. if ( isHighPrecisionModelViewMatrix !== true ) {
  7539. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7540. }
  7541. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7542. } );
  7543. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7544. /** @module Position **/
  7545. /**
  7546. * TSL object that represents the position attribute of the current rendered object.
  7547. *
  7548. * @type {AttributeNode<vec3>}
  7549. */
  7550. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7551. /**
  7552. * TSL object that represents the vertex position in local space of the current rendered object.
  7553. *
  7554. * @type {AttributeNode<vec3>}
  7555. */
  7556. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7557. /**
  7558. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7559. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7560. *
  7561. * @type {AttributeNode<vec3>}
  7562. */
  7563. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7564. /**
  7565. * TSL object that represents the vertex position in world space of the current rendered object.
  7566. *
  7567. * @type {VaryingNode<vec3>}
  7568. */
  7569. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7570. /**
  7571. * TSL object that represents the position world direction of the current rendered object.
  7572. *
  7573. * @type {Node<vec3>}
  7574. */
  7575. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7576. /**
  7577. * TSL object that represents the vertex position in view space of the current rendered object.
  7578. *
  7579. * @type {VaryingNode<vec3>}
  7580. */
  7581. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7582. return builder.context.setupPositionView();
  7583. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7584. /**
  7585. * TSL object that represents the position view direction of the current rendered object.
  7586. *
  7587. * @type {VaryingNode<vec3>}
  7588. */
  7589. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7590. /** @module FrontFacingNode **/
  7591. /**
  7592. * This node can be used to evaluate whether a primitive is front or back facing.
  7593. *
  7594. * @augments Node
  7595. */
  7596. class FrontFacingNode extends Node {
  7597. static get type() {
  7598. return 'FrontFacingNode';
  7599. }
  7600. /**
  7601. * Constructs a new front facing node.
  7602. */
  7603. constructor() {
  7604. super( 'bool' );
  7605. /**
  7606. * This flag can be used for type testing.
  7607. *
  7608. * @type {Boolean}
  7609. * @readonly
  7610. * @default true
  7611. */
  7612. this.isFrontFacingNode = true;
  7613. }
  7614. generate( builder ) {
  7615. const { renderer, material } = builder;
  7616. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7617. if ( material.side === BackSide ) {
  7618. return 'false';
  7619. }
  7620. }
  7621. return builder.getFrontFacing();
  7622. }
  7623. }
  7624. /**
  7625. * TSL object that represents whether a primitive is front or back facing
  7626. *
  7627. * @type {FrontFacingNode<bool>}
  7628. */
  7629. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7630. /**
  7631. * TSL object that represents the front facing status as a number instead of a bool.
  7632. * `1` means front facing, `-1` means back facing.
  7633. *
  7634. * @type {Node<float>}
  7635. */
  7636. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7637. /** @module Normal **/
  7638. /**
  7639. * TSL object that represents the normal attribute of the current rendered object.
  7640. *
  7641. * @type {Node<vec3>}
  7642. */
  7643. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7644. /**
  7645. * TSL object that represents the vertex normal in local space of the current rendered object.
  7646. *
  7647. * @type {Node<vec3>}
  7648. */
  7649. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7650. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7651. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7652. return vec3( 0, 1, 0 );
  7653. }
  7654. return normalGeometry;
  7655. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7656. /**
  7657. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7658. *
  7659. * @type {Node<vec3>}
  7660. */
  7661. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7662. /**
  7663. * TSL object that represents the vertex normal in view space of the current rendered object.
  7664. *
  7665. * @type {Node<vec3>}
  7666. */
  7667. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7668. let node;
  7669. if ( builder.material.flatShading === true ) {
  7670. node = normalFlat;
  7671. } else {
  7672. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7673. }
  7674. return node;
  7675. }, 'vec3' ).once() )().toVar( 'normalView' );
  7676. /**
  7677. * TSL object that represents the vertex normal in world space of the current rendered object.
  7678. *
  7679. * @type {Node<vec3>}
  7680. */
  7681. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7682. /**
  7683. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7684. *
  7685. * @type {Node<vec3>}
  7686. */
  7687. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7688. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7689. return builder.context.setupNormal().context( { getUV: null } );
  7690. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7691. /**
  7692. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7693. *
  7694. * @type {Node<vec3>}
  7695. */
  7696. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7697. /**
  7698. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7699. *
  7700. * @type {Node<vec3>}
  7701. */
  7702. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7703. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7704. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7705. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7706. /**
  7707. * Transforms the normal with the given matrix.
  7708. *
  7709. * @function
  7710. * @param {Node<vec3>} normal - The normal.
  7711. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7712. * @return {Node<vec3>} The transformed normal.
  7713. */
  7714. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7715. const m = mat3( matrix );
  7716. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7717. return m.mul( transformedNormal ).xyz;
  7718. } );
  7719. /**
  7720. * Transforms the given normal from local to view space.
  7721. *
  7722. * @function
  7723. * @param {Node<vec3>} normal - The normal.
  7724. * @param {NodeBuilder} builder - The current node builder.
  7725. * @return {Node<vec3>} The transformed normal.
  7726. */
  7727. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7728. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7729. if ( modelNormalViewMatrix !== null ) {
  7730. return modelNormalViewMatrix.transformDirection( normal );
  7731. }
  7732. //
  7733. const transformedNormal = modelNormalMatrix.mul( normal );
  7734. return cameraViewMatrix.transformDirection( transformedNormal );
  7735. } );
  7736. /** @module MaterialProperties **/
  7737. /**
  7738. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7739. *
  7740. * @type {UniformNode<float>}
  7741. */
  7742. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7743. /** @module ReflectVector **/
  7744. /**
  7745. * The reflect vector in view space.
  7746. *
  7747. * @type {Node<vec3>}
  7748. */
  7749. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7750. /**
  7751. * The refract vector in view space.
  7752. *
  7753. * @type {Node<vec3>}
  7754. */
  7755. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7756. /**
  7757. * Used for sampling cube maps when using cube reflection mapping.
  7758. *
  7759. * @type {Node<vec3>}
  7760. */
  7761. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7762. /**
  7763. * Used for sampling cube maps when using cube refraction mapping.
  7764. *
  7765. * @type {Node<vec3>}
  7766. */
  7767. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7768. /** @module CubeTextureNode **/
  7769. /**
  7770. * This type of uniform node represents a cube texture.
  7771. *
  7772. * @augments module:TextureNode~TextureNode
  7773. */
  7774. class CubeTextureNode extends TextureNode {
  7775. static get type() {
  7776. return 'CubeTextureNode';
  7777. }
  7778. /**
  7779. * Constructs a new cube texture node.
  7780. *
  7781. * @param {CubeTexture} value - The cube texture.
  7782. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7783. * @param {Node<int>?} [levelNode=null] - The level node.
  7784. * @param {Node<float>?} [biasNode=null] - The bias node.
  7785. */
  7786. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7787. super( value, uvNode, levelNode, biasNode );
  7788. /**
  7789. * This flag can be used for type testing.
  7790. *
  7791. * @type {Boolean}
  7792. * @readonly
  7793. * @default true
  7794. */
  7795. this.isCubeTextureNode = true;
  7796. }
  7797. /**
  7798. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7799. *
  7800. * @param {NodeBuilder} builder - The current node builder.
  7801. * @return {String} The input type.
  7802. */
  7803. getInputType( /*builder*/ ) {
  7804. return 'cubeTexture';
  7805. }
  7806. /**
  7807. * Returns a default uvs based on the mapping type of the cube texture.
  7808. *
  7809. * @return {Node<vec3>} The default uv attribute.
  7810. */
  7811. getDefaultUV() {
  7812. const texture = this.value;
  7813. if ( texture.mapping === CubeReflectionMapping ) {
  7814. return reflectVector;
  7815. } else if ( texture.mapping === CubeRefractionMapping ) {
  7816. return refractVector;
  7817. } else {
  7818. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7819. return vec3( 0, 0, 0 );
  7820. }
  7821. }
  7822. /**
  7823. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7824. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7825. *
  7826. * @param {Boolean} value - The update toggle.
  7827. */
  7828. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7829. /**
  7830. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7831. * to modify the uv node for correct sampling.
  7832. *
  7833. * @param {NodeBuilder} builder - The current node builder.
  7834. * @param {Node} uvNode - The uv node to setup.
  7835. * @return {Node} The updated uv node.
  7836. */
  7837. setupUV( builder, uvNode ) {
  7838. const texture = this.value;
  7839. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7840. return vec3( uvNode.x.negate(), uvNode.yz );
  7841. } else {
  7842. return uvNode;
  7843. }
  7844. }
  7845. /**
  7846. * Generates the uv code snippet.
  7847. *
  7848. * @param {NodeBuilder} builder - The current node builder.
  7849. * @param {Node} cubeUV - The uv node to generate code for.
  7850. * @return {String} The generated code snippet.
  7851. */
  7852. generateUV( builder, cubeUV ) {
  7853. return cubeUV.build( builder, 'vec3' );
  7854. }
  7855. }
  7856. /**
  7857. * TSL function for creating a cube texture node.
  7858. *
  7859. * @function
  7860. * @param {CubeTexture} value - The cube texture.
  7861. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7862. * @param {Node<int>?} [levelNode=null] - The level node.
  7863. * @param {Node<float>?} [biasNode=null] - The bias node.
  7864. * @returns {CubeTextureNode}
  7865. */
  7866. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7867. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7868. /** @module ReferenceNode **/
  7869. /**
  7870. * This class is only relevant if the referenced property is array-like.
  7871. * In this case, `ReferenceElementNode` allows to refer to a specific
  7872. * element inside the data structure via an index.
  7873. *
  7874. * @augments ArrayElementNode
  7875. */
  7876. class ReferenceElementNode extends ArrayElementNode {
  7877. static get type() {
  7878. return 'ReferenceElementNode';
  7879. }
  7880. /**
  7881. * Constructs a new reference element node.
  7882. *
  7883. * @param {ReferenceNode?} referenceNode - The reference node.
  7884. * @param {Node} indexNode - The index node that defines the element access.
  7885. */
  7886. constructor( referenceNode, indexNode ) {
  7887. super( referenceNode, indexNode );
  7888. /**
  7889. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7890. * property references to the current node.
  7891. *
  7892. * @type {ReferenceNode?}
  7893. * @default null
  7894. */
  7895. this.referenceNode = referenceNode;
  7896. /**
  7897. * This flag can be used for type testing.
  7898. *
  7899. * @type {Boolean}
  7900. * @readonly
  7901. * @default true
  7902. */
  7903. this.isReferenceElementNode = true;
  7904. }
  7905. /**
  7906. * This method is overwritten since the node type is inferred from
  7907. * the uniform type of the reference node.
  7908. *
  7909. * @return {String} The node type.
  7910. */
  7911. getNodeType() {
  7912. return this.referenceNode.uniformType;
  7913. }
  7914. generate( builder ) {
  7915. const snippet = super.generate( builder );
  7916. const arrayType = this.referenceNode.getNodeType();
  7917. const elementType = this.getNodeType();
  7918. return builder.format( snippet, arrayType, elementType );
  7919. }
  7920. }
  7921. /**
  7922. * This type of node establishes a reference to a property of another object.
  7923. * In this way, the value of the node is automatically linked to the value of
  7924. * referenced object. Reference nodes internally represent the linked value
  7925. * as a uniform.
  7926. *
  7927. * @augments Node
  7928. */
  7929. class ReferenceNode extends Node {
  7930. static get type() {
  7931. return 'ReferenceNode';
  7932. }
  7933. /**
  7934. * Constructs a new reference node.
  7935. *
  7936. * @param {String} property - The name of the property the node refers to.
  7937. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7938. * @param {Object?} [object=null] - The object the property belongs to.
  7939. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7940. */
  7941. constructor( property, uniformType, object = null, count = null ) {
  7942. super();
  7943. /**
  7944. * The name of the property the node refers to.
  7945. *
  7946. * @type {String}
  7947. */
  7948. this.property = property;
  7949. /**
  7950. * The uniform type that should be used to represent the property value.
  7951. *
  7952. * @type {String}
  7953. */
  7954. this.uniformType = uniformType;
  7955. /**
  7956. * The object the property belongs to.
  7957. *
  7958. * @type {Object?}
  7959. * @default null
  7960. */
  7961. this.object = object;
  7962. /**
  7963. * When the linked property is an array, this parameter defines its length.
  7964. *
  7965. * @type {Number?}
  7966. * @default null
  7967. */
  7968. this.count = count;
  7969. /**
  7970. * The property name might have dots so nested properties can be referred.
  7971. * The hierarchy of the names is stored inside this array.
  7972. *
  7973. * @type {Array<String>}
  7974. */
  7975. this.properties = property.split( '.' );
  7976. /**
  7977. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7978. * since the final reference might be updated from calling code.
  7979. *
  7980. * @type {Object?}
  7981. * @default null
  7982. */
  7983. this.reference = object;
  7984. /**
  7985. * The uniform node that holds the value of the reference node.
  7986. *
  7987. * @type {UniformNode}
  7988. * @default null
  7989. */
  7990. this.node = null;
  7991. /**
  7992. * The uniform group of the internal uniform.
  7993. *
  7994. * @type {UniformGroupNode}
  7995. * @default null
  7996. */
  7997. this.group = null;
  7998. /**
  7999. * An optional label of the internal uniform node.
  8000. *
  8001. * @type {String?}
  8002. * @default null
  8003. */
  8004. this.name = null;
  8005. /**
  8006. * Overwritten since reference nodes are updated per object.
  8007. *
  8008. * @type {String}
  8009. * @default 'object'
  8010. */
  8011. this.updateType = NodeUpdateType.OBJECT;
  8012. }
  8013. /**
  8014. * When the referred property is array-like, this method can be used
  8015. * to access elements via an index node.
  8016. *
  8017. * @param {IndexNode} indexNode - indexNode.
  8018. * @return {ReferenceElementNode} A reference to an element.
  8019. */
  8020. element( indexNode ) {
  8021. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8022. }
  8023. /**
  8024. * Sets the uniform group for this reference node.
  8025. *
  8026. * @param {UniformGroupNode} group - The uniform group to set.
  8027. * @return {ReferenceNode} A reference to this node.
  8028. */
  8029. setGroup( group ) {
  8030. this.group = group;
  8031. return this;
  8032. }
  8033. /**
  8034. * Sets the label for the internal uniform.
  8035. *
  8036. * @param {String} name - The label to set.
  8037. * @return {ReferenceNode} A reference to this node.
  8038. */
  8039. label( name ) {
  8040. this.name = name;
  8041. return this;
  8042. }
  8043. /**
  8044. * Sets the node type which automatically defines the internal
  8045. * uniform type.
  8046. *
  8047. * @param {String} uniformType - The type to set.
  8048. */
  8049. setNodeType( uniformType ) {
  8050. let node = null;
  8051. if ( this.count !== null ) {
  8052. node = buffer( null, uniformType, this.count );
  8053. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8054. node = uniformArray( null, uniformType );
  8055. } else if ( uniformType === 'texture' ) {
  8056. node = texture( null );
  8057. } else if ( uniformType === 'cubeTexture' ) {
  8058. node = cubeTexture( null );
  8059. } else {
  8060. node = uniform( null, uniformType );
  8061. }
  8062. if ( this.group !== null ) {
  8063. node.setGroup( this.group );
  8064. }
  8065. if ( this.name !== null ) node.label( this.name );
  8066. this.node = node.getSelf();
  8067. }
  8068. /**
  8069. * This method is overwritten since the node type is inferred from
  8070. * the type of the reference node.
  8071. *
  8072. * @param {NodeBuilder} builder - The current node builder.
  8073. * @return {String} The node type.
  8074. */
  8075. getNodeType( builder ) {
  8076. if ( this.node === null ) {
  8077. this.updateReference( builder );
  8078. this.updateValue();
  8079. }
  8080. return this.node.getNodeType( builder );
  8081. }
  8082. /**
  8083. * Returns the property value from the given referred object.
  8084. *
  8085. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8086. * @return {Any} The value.
  8087. */
  8088. getValueFromReference( object = this.reference ) {
  8089. const { properties } = this;
  8090. let value = object[ properties[ 0 ] ];
  8091. for ( let i = 1; i < properties.length; i ++ ) {
  8092. value = value[ properties[ i ] ];
  8093. }
  8094. return value;
  8095. }
  8096. /**
  8097. * Allows to update the reference based on the given state. The state is only
  8098. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8099. *
  8100. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8101. * @return {Object} The updated reference.
  8102. */
  8103. updateReference( state ) {
  8104. this.reference = this.object !== null ? this.object : state.object;
  8105. return this.reference;
  8106. }
  8107. /**
  8108. * The output of the reference node is the internal uniform node.
  8109. *
  8110. * @param {NodeBuilder} builder - The current node builder.
  8111. * @return {UniformNode} The output node.
  8112. */
  8113. setup( /* builder */ ) {
  8114. this.updateValue();
  8115. return this.node;
  8116. }
  8117. /**
  8118. * Overwritten to to update the internal uniform value.
  8119. *
  8120. * @param {NodeFrame} frame - A reference to the current node frame.
  8121. */
  8122. update( /*frame*/ ) {
  8123. this.updateValue();
  8124. }
  8125. /**
  8126. * Retrieves the value from the referred object property and uses it
  8127. * to updated the internal uniform.
  8128. */
  8129. updateValue() {
  8130. if ( this.node === null ) this.setNodeType( this.uniformType );
  8131. const value = this.getValueFromReference();
  8132. if ( Array.isArray( value ) ) {
  8133. this.node.array = value;
  8134. } else {
  8135. this.node.value = value;
  8136. }
  8137. }
  8138. }
  8139. /**
  8140. * TSL function for creating a reference node.
  8141. *
  8142. * @function
  8143. * @param {String} name - The name of the property the node refers to.
  8144. * @param {String} type - The uniform type that should be used to represent the property value.
  8145. * @param {Object} object - The object the property belongs to.
  8146. * @returns {ReferenceNode}
  8147. */
  8148. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8149. /**
  8150. * TSL function for creating a reference node. Use this function if you want need a reference
  8151. * to an array-like property that should be represented as a uniform buffer.
  8152. *
  8153. * @function
  8154. * @param {String} name - The name of the property the node refers to.
  8155. * @param {String} type - The uniform type that should be used to represent the property value.
  8156. * @param {Number} count - The number of value inside the array-like object.
  8157. * @param {Object} object - An array-like object the property belongs to.
  8158. * @returns {ReferenceNode}
  8159. */
  8160. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8161. /** @module MaterialReferenceNode **/
  8162. /**
  8163. * This node is a special type of reference node which is intended
  8164. * for linking material properties with node values.
  8165. * ```js
  8166. * const opacityNode = materialReference( 'opacity', 'float', material );
  8167. * ```
  8168. * When changing `material.opacity`, the node value of `opacityNode` will
  8169. * automatically be updated.
  8170. *
  8171. * @augments module:ReferenceNode~ReferenceNode
  8172. */
  8173. class MaterialReferenceNode extends ReferenceNode {
  8174. static get type() {
  8175. return 'MaterialReferenceNode';
  8176. }
  8177. /**
  8178. * Constructs a new material reference node.
  8179. *
  8180. * @param {String} property - The name of the property the node refers to.
  8181. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8182. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8183. * the node refers to the material of the current rendered object.
  8184. */
  8185. constructor( property, inputType, material = null ) {
  8186. super( property, inputType, material );
  8187. /**
  8188. * The material the property belongs to. When no material is set,
  8189. * the node refers to the material of the current rendered object.
  8190. *
  8191. * @type {Material?}
  8192. * @default null
  8193. */
  8194. this.material = material;
  8195. /**
  8196. * This flag can be used for type testing.
  8197. *
  8198. * @type {Boolean}
  8199. * @readonly
  8200. * @default true
  8201. */
  8202. this.isMaterialReferenceNode = true;
  8203. }
  8204. /**
  8205. * Updates the reference based on the given state. The state is only evaluated
  8206. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8207. *
  8208. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8209. * @return {Object} The updated reference.
  8210. */
  8211. updateReference( state ) {
  8212. this.reference = this.material !== null ? this.material : state.material;
  8213. return this.reference;
  8214. }
  8215. }
  8216. /**
  8217. * TSL function for creating a material reference node.
  8218. *
  8219. * @function
  8220. * @param {String} name - The name of the property the node refers to.
  8221. * @param {String} type - The uniform type that should be used to represent the property value.
  8222. * @param {Material?} [material=null] - The material the property belongs to.
  8223. * When no material is set, the node refers to the material of the current rendered object.
  8224. * @returns {MaterialReferenceNode}
  8225. */
  8226. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8227. /** @module Tangent **/
  8228. /**
  8229. * TSL object that represents the tangent attribute of the current rendered object.
  8230. *
  8231. * @type {Node<vec4>}
  8232. */
  8233. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8234. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8235. builder.geometry.computeTangents();
  8236. }
  8237. return attribute( 'tangent', 'vec4' );
  8238. } )();
  8239. /**
  8240. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8241. *
  8242. * @type {Node<vec3>}
  8243. */
  8244. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8245. /**
  8246. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8247. *
  8248. * @type {Node<vec3>}
  8249. */
  8250. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8251. /**
  8252. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8253. *
  8254. * @type {Node<vec3>}
  8255. */
  8256. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8257. /**
  8258. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8259. *
  8260. * @type {Node<vec3>}
  8261. */
  8262. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8263. /**
  8264. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8265. *
  8266. * @type {Node<vec3>}
  8267. */
  8268. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8269. /** @module Bitangent **/
  8270. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8271. /**
  8272. * TSL object that represents the bitangent attribute of the current rendered object.
  8273. *
  8274. * @type {Node<vec3>}
  8275. */
  8276. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8277. /**
  8278. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8279. *
  8280. * @type {Node<vec3>}
  8281. */
  8282. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8283. /**
  8284. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8285. *
  8286. * @type {Node<vec4>}
  8287. */
  8288. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8289. /**
  8290. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8291. *
  8292. * @type {Node<vec4>}
  8293. */
  8294. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8295. /**
  8296. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8297. *
  8298. * @type {Node<vec4>}
  8299. */
  8300. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8301. /**
  8302. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8303. *
  8304. * @type {Node<vec4>}
  8305. */
  8306. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8307. /** @module AccessorsUtils **/
  8308. /**
  8309. * TSL object that represents the TBN matrix in view space.
  8310. *
  8311. * @type {Node<mat3>}
  8312. */
  8313. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8314. /**
  8315. * TSL object that represents the parallax direction.
  8316. *
  8317. * @type {Node<mat3>}
  8318. */
  8319. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8320. /**
  8321. * TSL function for computing parallax uv coordinates.
  8322. *
  8323. * @function
  8324. * @param {Node<vec2>} uv - A uv node.
  8325. * @param {Node<vec2>} scale - A scale node.
  8326. * @returns {Node<vec2>} Parallax uv coordinates.
  8327. */
  8328. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8329. /**
  8330. * TSL function for computing bent normals.
  8331. *
  8332. * @function
  8333. * @returns {Node<vec3>} Bent normals.
  8334. */
  8335. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8336. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8337. let bentNormal = anisotropyB.cross( positionViewDirection );
  8338. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8339. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8340. return bentNormal;
  8341. } )();
  8342. /** @module NormalMapNode **/
  8343. // Normal Mapping Without Precomputed Tangents
  8344. // http://www.thetenthplanet.de/archives/1180
  8345. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8346. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8347. const q0 = eye_pos.dFdx();
  8348. const q1 = eye_pos.dFdy();
  8349. const st0 = uv.dFdx();
  8350. const st1 = uv.dFdy();
  8351. const N = surf_norm; // normalized
  8352. const q1perp = q1.cross( N );
  8353. const q0perp = N.cross( q0 );
  8354. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8355. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8356. const det = T.dot( T ).max( B.dot( B ) );
  8357. const scale = faceDirection.mul( det.inverseSqrt() );
  8358. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8359. } );
  8360. /**
  8361. * This class can be used for applying normals maps to materials.
  8362. *
  8363. * ```js
  8364. * material.normalNode = normalMap( texture( normalTex ) );
  8365. * ```
  8366. *
  8367. * @augments TempNode
  8368. */
  8369. class NormalMapNode extends TempNode {
  8370. static get type() {
  8371. return 'NormalMapNode';
  8372. }
  8373. /**
  8374. * Constructs a new normal map node.
  8375. *
  8376. * @param {Node<vec3>} node - Represents the normal map data.
  8377. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8378. */
  8379. constructor( node, scaleNode = null ) {
  8380. super( 'vec3' );
  8381. /**
  8382. * Represents the normal map data.
  8383. *
  8384. * @type {Node<vec3>}
  8385. */
  8386. this.node = node;
  8387. /**
  8388. * Controls the intensity of the effect.
  8389. *
  8390. * @type {Node<vec2>?}
  8391. * @default null
  8392. */
  8393. this.scaleNode = scaleNode;
  8394. /**
  8395. * The normal map type.
  8396. *
  8397. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8398. * @default TangentSpaceNormalMap
  8399. */
  8400. this.normalMapType = TangentSpaceNormalMap;
  8401. }
  8402. setup( builder ) {
  8403. const { normalMapType, scaleNode } = this;
  8404. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8405. if ( scaleNode !== null ) {
  8406. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8407. }
  8408. let outputNode = null;
  8409. if ( normalMapType === ObjectSpaceNormalMap ) {
  8410. outputNode = transformNormalToView( normalMap );
  8411. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8412. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8413. if ( tangent === true ) {
  8414. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8415. } else {
  8416. outputNode = perturbNormal2Arb( {
  8417. eye_pos: positionView,
  8418. surf_norm: normalView,
  8419. mapN: normalMap,
  8420. uv: uv()
  8421. } );
  8422. }
  8423. }
  8424. return outputNode;
  8425. }
  8426. }
  8427. /**
  8428. * TSL function for creating a normal map node.
  8429. *
  8430. * @function
  8431. * @param {Node<vec3>} node - Represents the normal map data.
  8432. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8433. * @returns {NormalMapNode}
  8434. */
  8435. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8436. /** @module BumpMapNode **/
  8437. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8438. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8439. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8440. // It's used to preserve the same TextureNode instance
  8441. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8442. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8443. return vec2(
  8444. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8445. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8446. ).mul( bumpScale );
  8447. } );
  8448. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8449. const perturbNormalArb = Fn( ( inputs ) => {
  8450. const { surf_pos, surf_norm, dHdxy } = inputs;
  8451. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8452. const vSigmaX = surf_pos.dFdx().normalize();
  8453. const vSigmaY = surf_pos.dFdy().normalize();
  8454. const vN = surf_norm; // normalized
  8455. const R1 = vSigmaY.cross( vN );
  8456. const R2 = vN.cross( vSigmaX );
  8457. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8458. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8459. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8460. } );
  8461. /**
  8462. * This class can be used for applying bump maps to materials.
  8463. *
  8464. * ```js
  8465. * material.normalNode = bumpMap( texture( bumpTex ) );
  8466. * ```
  8467. *
  8468. * @augments TempNode
  8469. */
  8470. class BumpMapNode extends TempNode {
  8471. static get type() {
  8472. return 'BumpMapNode';
  8473. }
  8474. /**
  8475. * Constructs a new bump map node.
  8476. *
  8477. * @param {Node<float>} textureNode - Represents the bump map data.
  8478. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8479. */
  8480. constructor( textureNode, scaleNode = null ) {
  8481. super( 'vec3' );
  8482. /**
  8483. * Represents the bump map data.
  8484. *
  8485. * @type {Node<float>}
  8486. */
  8487. this.textureNode = textureNode;
  8488. /**
  8489. * Controls the intensity of the bump effect.
  8490. *
  8491. * @type {Node<float>?}
  8492. * @default null
  8493. */
  8494. this.scaleNode = scaleNode;
  8495. }
  8496. setup() {
  8497. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8498. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8499. return perturbNormalArb( {
  8500. surf_pos: positionView,
  8501. surf_norm: normalView,
  8502. dHdxy
  8503. } );
  8504. }
  8505. }
  8506. /**
  8507. * TSL function for creating a bump map node.
  8508. *
  8509. * @function
  8510. * @param {Node<float>} textureNode - Represents the bump map data.
  8511. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8512. * @returns {BumpMapNode}
  8513. */
  8514. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8515. /** @module MaterialNode **/
  8516. const _propertyCache = new Map();
  8517. /**
  8518. * This class should simplify the node access to material properties.
  8519. * It internal uses reference nodes to make sure changes to material
  8520. * properties are automatically reflected to predefined TSL objects
  8521. * like e.g. `materialColor`.
  8522. *
  8523. * @augments Node
  8524. */
  8525. class MaterialNode extends Node {
  8526. static get type() {
  8527. return 'MaterialNode';
  8528. }
  8529. /**
  8530. * Constructs a new material node.
  8531. *
  8532. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8533. */
  8534. constructor( scope ) {
  8535. super();
  8536. /**
  8537. * The scope defines what material property is referred by the node.
  8538. *
  8539. * @type {String}
  8540. */
  8541. this.scope = scope;
  8542. }
  8543. /**
  8544. * Returns a cached reference node for the given property and type.
  8545. *
  8546. * @param {String} property - The name of the material property.
  8547. * @param {String} type - The uniform type of the property.
  8548. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8549. */
  8550. getCache( property, type ) {
  8551. let node = _propertyCache.get( property );
  8552. if ( node === undefined ) {
  8553. node = materialReference( property, type );
  8554. _propertyCache.set( property, node );
  8555. }
  8556. return node;
  8557. }
  8558. /**
  8559. * Returns a float-typed material reference node for the given property name.
  8560. *
  8561. * @param {String} property - The name of the material property.
  8562. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8563. */
  8564. getFloat( property ) {
  8565. return this.getCache( property, 'float' );
  8566. }
  8567. /**
  8568. * Returns a color-typed material reference node for the given property name.
  8569. *
  8570. * @param {String} property - The name of the material property.
  8571. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8572. */
  8573. getColor( property ) {
  8574. return this.getCache( property, 'color' );
  8575. }
  8576. /**
  8577. * Returns a texture-typed material reference node for the given property name.
  8578. *
  8579. * @param {String} property - The name of the material property.
  8580. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8581. */
  8582. getTexture( property ) {
  8583. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8584. }
  8585. /**
  8586. * The node setup is done depending on the selected scope. Multiple material properties
  8587. * might be grouped into a single node composition if they logically belong together.
  8588. *
  8589. * @param {NodeBuilder} builder - The current node builder.
  8590. * @return {Node} The node representing the selected scope.
  8591. */
  8592. setup( builder ) {
  8593. const material = builder.context.material;
  8594. const scope = this.scope;
  8595. let node = null;
  8596. if ( scope === MaterialNode.COLOR ) {
  8597. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8598. if ( material.map && material.map.isTexture === true ) {
  8599. node = colorNode.mul( this.getTexture( 'map' ) );
  8600. } else {
  8601. node = colorNode;
  8602. }
  8603. } else if ( scope === MaterialNode.OPACITY ) {
  8604. const opacityNode = this.getFloat( scope );
  8605. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8606. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8607. } else {
  8608. node = opacityNode;
  8609. }
  8610. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8611. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8612. node = this.getTexture( 'specular' ).r;
  8613. } else {
  8614. node = float( 1 );
  8615. }
  8616. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8617. const specularIntensityNode = this.getFloat( scope );
  8618. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8619. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8620. } else {
  8621. node = specularIntensityNode;
  8622. }
  8623. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8624. const specularColorNode = this.getColor( scope );
  8625. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8626. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8627. } else {
  8628. node = specularColorNode;
  8629. }
  8630. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8631. const roughnessNode = this.getFloat( scope );
  8632. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8633. node = roughnessNode.mul( this.getTexture( scope ).g );
  8634. } else {
  8635. node = roughnessNode;
  8636. }
  8637. } else if ( scope === MaterialNode.METALNESS ) {
  8638. const metalnessNode = this.getFloat( scope );
  8639. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8640. node = metalnessNode.mul( this.getTexture( scope ).b );
  8641. } else {
  8642. node = metalnessNode;
  8643. }
  8644. } else if ( scope === MaterialNode.EMISSIVE ) {
  8645. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8646. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8647. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8648. node = emissiveNode.mul( this.getTexture( scope ) );
  8649. } else {
  8650. node = emissiveNode;
  8651. }
  8652. } else if ( scope === MaterialNode.NORMAL ) {
  8653. if ( material.normalMap ) {
  8654. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8655. node.normalMapType = material.normalMapType;
  8656. } else if ( material.bumpMap ) {
  8657. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8658. } else {
  8659. node = normalView;
  8660. }
  8661. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8662. const clearcoatNode = this.getFloat( scope );
  8663. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8664. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8665. } else {
  8666. node = clearcoatNode;
  8667. }
  8668. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8669. const clearcoatRoughnessNode = this.getFloat( scope );
  8670. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8671. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8672. } else {
  8673. node = clearcoatRoughnessNode;
  8674. }
  8675. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8676. if ( material.clearcoatNormalMap ) {
  8677. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8678. } else {
  8679. node = normalView;
  8680. }
  8681. } else if ( scope === MaterialNode.SHEEN ) {
  8682. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8683. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8684. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8685. } else {
  8686. node = sheenNode;
  8687. }
  8688. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8689. const sheenRoughnessNode = this.getFloat( scope );
  8690. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8691. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8692. } else {
  8693. node = sheenRoughnessNode;
  8694. }
  8695. node = node.clamp( 0.07, 1.0 );
  8696. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8697. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8698. const anisotropyPolar = this.getTexture( scope );
  8699. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8700. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8701. } else {
  8702. node = materialAnisotropyVector;
  8703. }
  8704. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8705. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8706. if ( material.iridescenceThicknessMap ) {
  8707. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8708. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8709. } else {
  8710. node = iridescenceThicknessMaximum;
  8711. }
  8712. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8713. const transmissionNode = this.getFloat( scope );
  8714. if ( material.transmissionMap ) {
  8715. node = transmissionNode.mul( this.getTexture( scope ).r );
  8716. } else {
  8717. node = transmissionNode;
  8718. }
  8719. } else if ( scope === MaterialNode.THICKNESS ) {
  8720. const thicknessNode = this.getFloat( scope );
  8721. if ( material.thicknessMap ) {
  8722. node = thicknessNode.mul( this.getTexture( scope ).g );
  8723. } else {
  8724. node = thicknessNode;
  8725. }
  8726. } else if ( scope === MaterialNode.IOR ) {
  8727. node = this.getFloat( scope );
  8728. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8729. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8730. } else if ( scope === MaterialNode.AO ) {
  8731. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8732. } else {
  8733. const outputType = this.getNodeType( builder );
  8734. node = this.getCache( scope, outputType );
  8735. }
  8736. return node;
  8737. }
  8738. }
  8739. MaterialNode.ALPHA_TEST = 'alphaTest';
  8740. MaterialNode.COLOR = 'color';
  8741. MaterialNode.OPACITY = 'opacity';
  8742. MaterialNode.SHININESS = 'shininess';
  8743. MaterialNode.SPECULAR = 'specular';
  8744. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8745. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8746. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8747. MaterialNode.REFLECTIVITY = 'reflectivity';
  8748. MaterialNode.ROUGHNESS = 'roughness';
  8749. MaterialNode.METALNESS = 'metalness';
  8750. MaterialNode.NORMAL = 'normal';
  8751. MaterialNode.CLEARCOAT = 'clearcoat';
  8752. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8753. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8754. MaterialNode.EMISSIVE = 'emissive';
  8755. MaterialNode.ROTATION = 'rotation';
  8756. MaterialNode.SHEEN = 'sheen';
  8757. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8758. MaterialNode.ANISOTROPY = 'anisotropy';
  8759. MaterialNode.IRIDESCENCE = 'iridescence';
  8760. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8761. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8762. MaterialNode.IOR = 'ior';
  8763. MaterialNode.TRANSMISSION = 'transmission';
  8764. MaterialNode.THICKNESS = 'thickness';
  8765. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8766. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8767. MaterialNode.LINE_SCALE = 'scale';
  8768. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8769. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8770. MaterialNode.LINE_WIDTH = 'linewidth';
  8771. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8772. MaterialNode.POINT_SIZE = 'size';
  8773. MaterialNode.DISPERSION = 'dispersion';
  8774. MaterialNode.LIGHT_MAP = 'light';
  8775. MaterialNode.AO = 'ao';
  8776. /**
  8777. * TSL object that represents alpha test of the current material.
  8778. *
  8779. * @type {Node<float>}
  8780. */
  8781. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8782. /**
  8783. * TSL object that represents the diffuse color of the current material.
  8784. * The value is composed via `color` * `map`.
  8785. *
  8786. * @type {Node<vec3>}
  8787. */
  8788. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8789. /**
  8790. * TSL object that represents the shininess of the current material.
  8791. *
  8792. * @type {Node<float>}
  8793. */
  8794. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8795. /**
  8796. * TSL object that represents the emissive color of the current material.
  8797. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8798. *
  8799. * @type {Node<vec3>}
  8800. */
  8801. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8802. /**
  8803. * TSL object that represents the opacity of the current material.
  8804. * The value is composed via `opacity` * `alphaMap`.
  8805. *
  8806. * @type {Node<float>}
  8807. */
  8808. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8809. /**
  8810. * TSL object that represents the specular of the current material.
  8811. *
  8812. * @type {Node<vec3>}
  8813. */
  8814. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8815. /**
  8816. * TSL object that represents the specular intensity of the current material.
  8817. * The value is composed via `specularIntensity` * `specularMap.a`.
  8818. *
  8819. * @type {Node<float>}
  8820. */
  8821. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8822. /**
  8823. * TSL object that represents the specular color of the current material.
  8824. * The value is composed via `specularColor` * `specularMap.rgb`.
  8825. *
  8826. * @type {Node<vec3>}
  8827. */
  8828. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8829. /**
  8830. * TSL object that represents the specular strength of the current material.
  8831. * The value is composed via `specularMap.r`.
  8832. *
  8833. * @type {Node<float>}
  8834. */
  8835. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8836. /**
  8837. * TSL object that represents the reflectivity of the current material.
  8838. *
  8839. * @type {Node<float>}
  8840. */
  8841. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8842. /**
  8843. * TSL object that represents the roughness of the current material.
  8844. * The value is composed via `roughness` * `roughnessMap.g`.
  8845. *
  8846. * @type {Node<float>}
  8847. */
  8848. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8849. /**
  8850. * TSL object that represents the metalness of the current material.
  8851. * The value is composed via `metalness` * `metalnessMap.b`.
  8852. *
  8853. * @type {Node<float>}
  8854. */
  8855. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8856. /**
  8857. * TSL object that represents the normal of the current material.
  8858. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8859. *
  8860. * @type {Node<vec3>}
  8861. */
  8862. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8863. /**
  8864. * TSL object that represents the clearcoat of the current material.
  8865. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8866. *
  8867. * @type {Node<float>}
  8868. */
  8869. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8870. /**
  8871. * TSL object that represents the clearcoat roughness of the current material.
  8872. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  8873. *
  8874. * @type {Node<float>}
  8875. */
  8876. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8877. /**
  8878. * TSL object that represents the clearcoat normal of the current material.
  8879. * The value will be either `clearcoatNormalMap` or `normalView`.
  8880. *
  8881. * @type {Node<vec3>}
  8882. */
  8883. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  8884. /**
  8885. * TSL object that represents the rotation of the current sprite material.
  8886. *
  8887. * @type {Node<float>}
  8888. */
  8889. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8890. /**
  8891. * TSL object that represents the sheen color of the current material.
  8892. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8893. *
  8894. * @type {Node<vec3>}
  8895. */
  8896. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8897. /**
  8898. * TSL object that represents the sheen roughness of the current material.
  8899. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  8900. *
  8901. * @type {Node<float>}
  8902. */
  8903. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8904. /**
  8905. * TSL object that represents the anisotropy of the current material.
  8906. *
  8907. * @type {Node<vec2>}
  8908. */
  8909. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8910. /**
  8911. * TSL object that represents the iridescence of the current material.
  8912. *
  8913. * @type {Node<float>}
  8914. */
  8915. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8916. /**
  8917. * TSL object that represents the iridescence IOR of the current material.
  8918. *
  8919. * @type {Node<float>}
  8920. */
  8921. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8922. /**
  8923. * TSL object that represents the iridescence thickness of the current material.
  8924. *
  8925. * @type {Node<float>}
  8926. */
  8927. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8928. /**
  8929. * TSL object that represents the transmission of the current material.
  8930. * The value is composed via `transmission` * `transmissionMap.r`.
  8931. *
  8932. * @type {Node<float>}
  8933. */
  8934. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8935. /**
  8936. * TSL object that represents the thickness of the current material.
  8937. * The value is composed via `thickness` * `thicknessMap.g`.
  8938. *
  8939. * @type {Node<float>}
  8940. */
  8941. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8942. /**
  8943. * TSL object that represents the IOR of the current material.
  8944. *
  8945. * @type {Node<float>}
  8946. */
  8947. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8948. /**
  8949. * TSL object that represents the attenuation distance of the current material.
  8950. *
  8951. * @type {Node<float>}
  8952. */
  8953. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8954. /**
  8955. * TSL object that represents the attenuation color of the current material.
  8956. *
  8957. * @type {Node<vec3>}
  8958. */
  8959. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8960. /**
  8961. * TSL object that represents the scale of the current dashed line material.
  8962. *
  8963. * @type {Node<float>}
  8964. */
  8965. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8966. /**
  8967. * TSL object that represents the dash size of the current dashed line material.
  8968. *
  8969. * @type {Node<float>}
  8970. */
  8971. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8972. /**
  8973. * TSL object that represents the gap size of the current dashed line material.
  8974. *
  8975. * @type {Node<float>}
  8976. */
  8977. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8978. /**
  8979. * TSL object that represents the line width of the current line material.
  8980. *
  8981. * @type {Node<float>}
  8982. */
  8983. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8984. /**
  8985. * TSL object that represents the dash offset of the current line material.
  8986. *
  8987. * @type {Node<float>}
  8988. */
  8989. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8990. /**
  8991. * TSL object that represents the point size of the current points material.
  8992. *
  8993. * @type {Node<float>}
  8994. */
  8995. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  8996. /**
  8997. * TSL object that represents the dispersion of the current material.
  8998. *
  8999. * @type {Node<float>}
  9000. */
  9001. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9002. /**
  9003. * TSL object that represents the light map of the current material.
  9004. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9005. *
  9006. * @type {Node<vec3>}
  9007. */
  9008. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9009. /**
  9010. * TSL object that represents the ambient occlusion map of the current material.
  9011. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9012. *
  9013. * @type {Node<float>}
  9014. */
  9015. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9016. /**
  9017. * TSL object that represents the anisotropy vector of the current material.
  9018. *
  9019. * @type {Node<vec2>}
  9020. */
  9021. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9022. return frame.material;
  9023. } ).onRenderUpdate( function ( { material } ) {
  9024. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9025. } );
  9026. /** @module ModelViewProjectionNode **/
  9027. /**
  9028. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9029. *
  9030. * @type {VaryingNode<vec4>}
  9031. */
  9032. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9033. return builder.context.setupModelViewProjection();
  9034. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  9035. /** @module IndexNode **/
  9036. /**
  9037. * This class represents shader indices of different types. The following predefined node
  9038. * objects cover frequent use cases:
  9039. *
  9040. * - `vertexIndex`: The index of a vertex within a mesh.
  9041. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9042. * - `drawIndex`: The index of a draw call.
  9043. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9044. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9045. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9046. *
  9047. * @augments Node
  9048. */
  9049. class IndexNode extends Node {
  9050. static get type() {
  9051. return 'IndexNode';
  9052. }
  9053. /**
  9054. * Constructs a new index node.
  9055. *
  9056. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9057. */
  9058. constructor( scope ) {
  9059. super( 'uint' );
  9060. /**
  9061. * The scope of the index node.
  9062. *
  9063. * @type {String}
  9064. */
  9065. this.scope = scope;
  9066. /**
  9067. * This flag can be used for type testing.
  9068. *
  9069. * @type {Boolean}
  9070. * @readonly
  9071. * @default true
  9072. */
  9073. this.isIndexNode = true;
  9074. }
  9075. generate( builder ) {
  9076. const nodeType = this.getNodeType( builder );
  9077. const scope = this.scope;
  9078. let propertyName;
  9079. if ( scope === IndexNode.VERTEX ) {
  9080. propertyName = builder.getVertexIndex();
  9081. } else if ( scope === IndexNode.INSTANCE ) {
  9082. propertyName = builder.getInstanceIndex();
  9083. } else if ( scope === IndexNode.DRAW ) {
  9084. propertyName = builder.getDrawIndex();
  9085. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9086. propertyName = builder.getInvocationLocalIndex();
  9087. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9088. propertyName = builder.getInvocationSubgroupIndex();
  9089. } else if ( scope === IndexNode.SUBGROUP ) {
  9090. propertyName = builder.getSubgroupIndex();
  9091. } else {
  9092. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9093. }
  9094. let output;
  9095. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9096. output = propertyName;
  9097. } else {
  9098. const nodeVarying = varying( this );
  9099. output = nodeVarying.build( builder, nodeType );
  9100. }
  9101. return output;
  9102. }
  9103. }
  9104. IndexNode.VERTEX = 'vertex';
  9105. IndexNode.INSTANCE = 'instance';
  9106. IndexNode.SUBGROUP = 'subgroup';
  9107. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9108. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9109. IndexNode.DRAW = 'draw';
  9110. /**
  9111. * TSL object that represents the index of a vertex within a mesh.
  9112. *
  9113. * @type {IndexNode}
  9114. */
  9115. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9116. /**
  9117. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9118. *
  9119. * @type {IndexNode}
  9120. */
  9121. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9122. /**
  9123. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9124. *
  9125. * @type {IndexNode}
  9126. */
  9127. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9128. /**
  9129. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9130. *
  9131. * @type {IndexNode}
  9132. */
  9133. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9134. /**
  9135. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9136. *
  9137. * @type {IndexNode}
  9138. */
  9139. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9140. /**
  9141. * TSL object that represents the index of a draw call.
  9142. *
  9143. * @type {IndexNode}
  9144. */
  9145. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9146. /** @module InstanceNode **/
  9147. /**
  9148. * This node implements the vertex shader logic which is required
  9149. * when rendering 3D objects via instancing. The code makes sure
  9150. * vertex positions, normals and colors can be modified via instanced
  9151. * data.
  9152. *
  9153. * @augments Node
  9154. */
  9155. class InstanceNode extends Node {
  9156. static get type() {
  9157. return 'InstanceNode';
  9158. }
  9159. /**
  9160. * Constructs a new instance node.
  9161. *
  9162. * @param {Number} count - The number of instances.
  9163. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9164. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9165. */
  9166. constructor( count, instanceMatrix, instanceColor ) {
  9167. super( 'void' );
  9168. /**
  9169. * The number of instances.
  9170. *
  9171. * @type {Number}
  9172. */
  9173. this.count = count;
  9174. /**
  9175. * Instanced buffer attribute representing the transformation of instances.
  9176. *
  9177. * @type {InstancedBufferAttribute}
  9178. */
  9179. this.instanceMatrix = instanceMatrix;
  9180. /**
  9181. * Instanced buffer attribute representing the color of instances.
  9182. *
  9183. * @type {InstancedBufferAttribute}
  9184. */
  9185. this.instanceColor = instanceColor;
  9186. /**
  9187. * The node that represents the instance matrix data.
  9188. *
  9189. * @type {Node}
  9190. */
  9191. this.instanceMatrixNode = null;
  9192. /**
  9193. * The node that represents the instance color data.
  9194. *
  9195. * @type {Node}
  9196. */
  9197. this.instanceColorNode = null;
  9198. /**
  9199. * The update type is set to `frame` since an update
  9200. * of instanced buffer data must be checked per frame.
  9201. *
  9202. * @type {String}
  9203. * @default 'frame'
  9204. */
  9205. this.updateType = NodeUpdateType.FRAME;
  9206. /**
  9207. * A reference to a buffer that is used by `instanceMatrixNode`.
  9208. *
  9209. * @type {InstancedInterleavedBuffer}
  9210. */
  9211. this.buffer = null;
  9212. /**
  9213. * A reference to a buffer that is used by `instanceColorNode`.
  9214. *
  9215. * @type {InstancedBufferAttribute}
  9216. */
  9217. this.bufferColor = null;
  9218. }
  9219. /**
  9220. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9221. * to predefined node variables for accumulation. That follows the same patterns
  9222. * like with morph and skinning nodes.
  9223. *
  9224. * @param {NodeBuilder} builder - The current node builder.
  9225. */
  9226. setup( builder ) {
  9227. const { count, instanceMatrix, instanceColor } = this;
  9228. let { instanceMatrixNode, instanceColorNode } = this;
  9229. if ( instanceMatrixNode === null ) {
  9230. // 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.
  9231. if ( count <= 1000 ) {
  9232. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9233. } else {
  9234. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9235. this.buffer = buffer;
  9236. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9237. const instanceBuffers = [
  9238. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9239. bufferFn( buffer, 'vec4', 16, 0 ),
  9240. bufferFn( buffer, 'vec4', 16, 4 ),
  9241. bufferFn( buffer, 'vec4', 16, 8 ),
  9242. bufferFn( buffer, 'vec4', 16, 12 )
  9243. ];
  9244. instanceMatrixNode = mat4( ...instanceBuffers );
  9245. }
  9246. this.instanceMatrixNode = instanceMatrixNode;
  9247. }
  9248. if ( instanceColor && instanceColorNode === null ) {
  9249. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9250. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9251. this.bufferColor = buffer;
  9252. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9253. this.instanceColorNode = instanceColorNode;
  9254. }
  9255. // POSITION
  9256. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9257. positionLocal.assign( instancePosition );
  9258. // NORMAL
  9259. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9260. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9261. // ASSIGNS
  9262. normalLocal.assign( instanceNormal );
  9263. }
  9264. // COLOR
  9265. if ( this.instanceColorNode !== null ) {
  9266. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9267. }
  9268. }
  9269. /**
  9270. * Checks if the internal buffers required an update.
  9271. *
  9272. * @param {NodeFrame} frame - The current node frame.
  9273. */
  9274. update( /*frame*/ ) {
  9275. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9276. this.buffer.version = this.instanceMatrix.version;
  9277. }
  9278. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9279. this.bufferColor.version = this.instanceColor.version;
  9280. }
  9281. }
  9282. }
  9283. /**
  9284. * TSL function for creating an instance node.
  9285. *
  9286. * @function
  9287. * @param {Number} count - The number of instances.
  9288. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9289. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9290. * @returns {InstanceNode}
  9291. */
  9292. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9293. /** @module InstancedMeshNode **/
  9294. /**
  9295. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9296. * It allows an easier setup of the instance node.
  9297. *
  9298. * @augments module:InstanceNode~InstanceNode
  9299. */
  9300. class InstancedMeshNode extends InstanceNode {
  9301. static get type() {
  9302. return 'InstancedMeshNode';
  9303. }
  9304. /**
  9305. * Constructs a new instanced mesh node.
  9306. *
  9307. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9308. */
  9309. constructor( instancedMesh ) {
  9310. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9311. super( count, instanceMatrix, instanceColor );
  9312. /**
  9313. * A reference to the instanced mesh.
  9314. *
  9315. * @type {InstancedMesh}
  9316. */
  9317. this.instancedMesh = instancedMesh;
  9318. }
  9319. }
  9320. /**
  9321. * TSL function for creating an instanced mesh node.
  9322. *
  9323. * @function
  9324. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9325. * @returns {InstancedMeshNode}
  9326. */
  9327. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9328. /** @module BatchNode **/
  9329. /**
  9330. * This node implements the vertex shader logic which is required
  9331. * when rendering 3D objects via batching. `BatchNode` must be used
  9332. * with instances of {@link BatchedMesh}.
  9333. *
  9334. * @augments Node
  9335. */
  9336. class BatchNode extends Node {
  9337. static get type() {
  9338. return 'BatchNode';
  9339. }
  9340. /**
  9341. * Constructs a new batch node.
  9342. *
  9343. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9344. */
  9345. constructor( batchMesh ) {
  9346. super( 'void' );
  9347. /**
  9348. * A reference to batched mesh.
  9349. *
  9350. * @type {BatchedMesh}
  9351. */
  9352. this.batchMesh = batchMesh;
  9353. /**
  9354. * The batching index node.
  9355. *
  9356. * @type {IndexNode?}
  9357. * @default null
  9358. */
  9359. this.batchingIdNode = null;
  9360. }
  9361. /**
  9362. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9363. * to predefined node variables for accumulation. That follows the same patterns
  9364. * like with morph and skinning nodes.
  9365. *
  9366. * @param {NodeBuilder} builder - The current node builder.
  9367. */
  9368. setup( builder ) {
  9369. if ( this.batchingIdNode === null ) {
  9370. if ( builder.getDrawIndex() === null ) {
  9371. this.batchingIdNode = instanceIndex;
  9372. } else {
  9373. this.batchingIdNode = drawIndex;
  9374. }
  9375. }
  9376. const getIndirectIndex = Fn( ( [ id ] ) => {
  9377. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9378. const x = int( id ).modInt( int( size ) );
  9379. const y = int( id ).div( int( size ) );
  9380. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9381. } ).setLayout( {
  9382. name: 'getIndirectIndex',
  9383. type: 'uint',
  9384. inputs: [
  9385. { name: 'id', type: 'int' }
  9386. ]
  9387. } );
  9388. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9389. const matricesTexture = this.batchMesh._matricesTexture;
  9390. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9391. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9392. const x = j.modInt( size );
  9393. const y = j.div( int( size ) );
  9394. const batchingMatrix = mat4(
  9395. textureLoad( matricesTexture, ivec2( x, y ) ),
  9396. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9397. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9398. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9399. );
  9400. const colorsTexture = this.batchMesh._colorsTexture;
  9401. if ( colorsTexture !== null ) {
  9402. const getBatchingColor = Fn( ( [ id ] ) => {
  9403. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9404. const j = id;
  9405. const x = j.modInt( size );
  9406. const y = j.div( size );
  9407. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9408. } ).setLayout( {
  9409. name: 'getBatchingColor',
  9410. type: 'vec3',
  9411. inputs: [
  9412. { name: 'id', type: 'int' }
  9413. ]
  9414. } );
  9415. const color = getBatchingColor( indirectId );
  9416. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9417. }
  9418. const bm = mat3( batchingMatrix );
  9419. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9420. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9421. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9422. normalLocal.assign( batchingNormal );
  9423. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9424. tangentLocal.mulAssign( bm );
  9425. }
  9426. }
  9427. }
  9428. /**
  9429. * TSL function for creating a batch node.
  9430. *
  9431. * @function
  9432. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9433. * @returns {BatchNode}
  9434. */
  9435. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9436. /** @module SkinningNode **/
  9437. const _frameId = new WeakMap();
  9438. /**
  9439. * This node implements the vertex transformation shader logic which is required
  9440. * for skinning/skeletal animation.
  9441. *
  9442. * @augments Node
  9443. */
  9444. class SkinningNode extends Node {
  9445. static get type() {
  9446. return 'SkinningNode';
  9447. }
  9448. /**
  9449. * Constructs a new skinning node.
  9450. *
  9451. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9452. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9453. */
  9454. constructor( skinnedMesh, useReference = false ) {
  9455. super( 'void' );
  9456. /**
  9457. * The skinned mesh.
  9458. *
  9459. * @type {SkinnedMesh}
  9460. */
  9461. this.skinnedMesh = skinnedMesh;
  9462. /**
  9463. * Whether to use reference nodes for internal skinned mesh related data or not.
  9464. * TODO: Explain the purpose of the property.
  9465. *
  9466. * @type {Boolean}
  9467. */
  9468. this.useReference = useReference;
  9469. /**
  9470. * The update type overwritten since skinning nodes are updated per object.
  9471. *
  9472. * @type {String}
  9473. */
  9474. this.updateType = NodeUpdateType.OBJECT;
  9475. //
  9476. /**
  9477. * The skin index attribute.
  9478. *
  9479. * @type {AttributeNode}
  9480. */
  9481. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9482. /**
  9483. * The skin weight attribute.
  9484. *
  9485. * @type {AttributeNode}
  9486. */
  9487. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9488. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9489. if ( useReference ) {
  9490. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9491. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9492. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9493. } else {
  9494. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9495. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9496. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9497. }
  9498. /**
  9499. * The bind matrix node.
  9500. *
  9501. * @type {Node<mat4>}
  9502. */
  9503. this.bindMatrixNode = bindMatrixNode;
  9504. /**
  9505. * The bind matrix inverse node.
  9506. *
  9507. * @type {Node<mat4>}
  9508. */
  9509. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9510. /**
  9511. * The bind matrices as a uniform buffer node.
  9512. *
  9513. * @type {Node}
  9514. */
  9515. this.boneMatricesNode = boneMatricesNode;
  9516. /**
  9517. * The previous bind matrices as a uniform buffer node.
  9518. * Required for computing motion vectors.
  9519. *
  9520. * @type {Node?}
  9521. * @default null
  9522. */
  9523. this.previousBoneMatricesNode = null;
  9524. }
  9525. /**
  9526. * Transforms the given vertex position via skinning.
  9527. *
  9528. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9529. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9530. * @return {Node<vec3>} The transformed vertex position.
  9531. */
  9532. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9533. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9534. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9535. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9536. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9537. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9538. // POSITION
  9539. const skinVertex = bindMatrixNode.mul( position );
  9540. const skinned = add(
  9541. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9542. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9543. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9544. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9545. );
  9546. return bindMatrixInverseNode.mul( skinned ).xyz;
  9547. }
  9548. /**
  9549. * Transforms the given vertex normal via skinning.
  9550. *
  9551. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9552. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9553. * @return {Node<vec3>} The transformed vertex normal.
  9554. */
  9555. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9556. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9557. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9558. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9559. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9560. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9561. // NORMAL
  9562. let skinMatrix = add(
  9563. skinWeightNode.x.mul( boneMatX ),
  9564. skinWeightNode.y.mul( boneMatY ),
  9565. skinWeightNode.z.mul( boneMatZ ),
  9566. skinWeightNode.w.mul( boneMatW )
  9567. );
  9568. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9569. return skinMatrix.transformDirection( normal ).xyz;
  9570. }
  9571. /**
  9572. * Transforms the given vertex normal via skinning.
  9573. *
  9574. * @param {NodeBuilder} builder - The current node builder.
  9575. * @return {Node<vec3>} The skinned position from the previous frame.
  9576. */
  9577. getPreviousSkinnedPosition( builder ) {
  9578. const skinnedMesh = builder.object;
  9579. if ( this.previousBoneMatricesNode === null ) {
  9580. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9581. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9582. }
  9583. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9584. }
  9585. /**
  9586. * Returns `true` if bone matrices from the previous frame are required.
  9587. *
  9588. * @param {NodeBuilder} builder - The current node builder.
  9589. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9590. */
  9591. needsPreviousBoneMatrices( builder ) {
  9592. const mrt = builder.renderer.getMRT();
  9593. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9594. }
  9595. /**
  9596. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9597. *
  9598. * @param {NodeBuilder} builder - The current node builder.
  9599. */
  9600. setup( builder ) {
  9601. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9602. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9603. }
  9604. const skinPosition = this.getSkinnedPosition();
  9605. positionLocal.assign( skinPosition );
  9606. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9607. const skinNormal = this.getSkinnedNormal();
  9608. normalLocal.assign( skinNormal );
  9609. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9610. tangentLocal.assign( skinNormal );
  9611. }
  9612. }
  9613. }
  9614. /**
  9615. * Generates the code snippet of the skinning node.
  9616. *
  9617. * @param {NodeBuilder} builder - The current node builder.
  9618. * @param {String} output - The current output.
  9619. * @return {String} The generated code snippet.
  9620. */
  9621. generate( builder, output ) {
  9622. if ( output !== 'void' ) {
  9623. return positionLocal.build( builder, output );
  9624. }
  9625. }
  9626. /**
  9627. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9628. *
  9629. * @param {NodeFrame} frame - The current node frame.
  9630. */
  9631. update( frame ) {
  9632. const object = this.useReference ? frame.object : this.skinnedMesh;
  9633. const skeleton = object.skeleton;
  9634. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9635. _frameId.set( skeleton, frame.frameId );
  9636. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9637. skeleton.update();
  9638. }
  9639. }
  9640. /**
  9641. * TSL function for creating a skinning node.
  9642. *
  9643. * @function
  9644. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9645. * @returns {SkinningNode}
  9646. */
  9647. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9648. /**
  9649. * TSL function for creating a skinning node with reference usage.
  9650. *
  9651. * @function
  9652. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9653. * @returns {SkinningNode}
  9654. */
  9655. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9656. /** @module LoopNode **/
  9657. /**
  9658. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9659. * ```js
  9660. * Loop( count, ( { i } ) => {
  9661. *
  9662. * } );
  9663. * ```
  9664. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9665. * ```js
  9666. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9667. *
  9668. * } );
  9669. *```
  9670. * Nested loops can be defined in a compacted form:
  9671. * ```js
  9672. * Loop( 10, 5, ( { i, j } ) => {
  9673. *
  9674. * } );
  9675. * ```
  9676. * Loops that should run backwards can be defined like so:
  9677. * ```js
  9678. * Loop( { start: 10 }, () => {} );
  9679. * ```
  9680. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9681. * @augments Node
  9682. */
  9683. class LoopNode extends Node {
  9684. static get type() {
  9685. return 'LoopNode';
  9686. }
  9687. /**
  9688. * Constructs a new loop node.
  9689. *
  9690. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9691. */
  9692. constructor( params = [] ) {
  9693. super();
  9694. this.params = params;
  9695. }
  9696. /**
  9697. * Returns a loop variable name based on an index. The pattern is
  9698. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9699. *
  9700. * @param {Number} index - The index.
  9701. * @return {String} The loop variable name.
  9702. */
  9703. getVarName( index ) {
  9704. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9705. }
  9706. /**
  9707. * Returns properties about this node.
  9708. *
  9709. * @param {NodeBuilder} builder - The current node builder.
  9710. * @return {Object} The node properties.
  9711. */
  9712. getProperties( builder ) {
  9713. const properties = builder.getNodeProperties( this );
  9714. if ( properties.stackNode !== undefined ) return properties;
  9715. //
  9716. const inputs = {};
  9717. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9718. const param = this.params[ i ];
  9719. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9720. const type = ( param.isNode !== true && param.type ) || 'int';
  9721. inputs[ name ] = expression( name, type );
  9722. }
  9723. const stack = builder.addStack(); // TODO: cache() it
  9724. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9725. properties.stackNode = stack;
  9726. builder.removeStack();
  9727. return properties;
  9728. }
  9729. /**
  9730. * This method is overwritten since the node type is inferred based on the loop configuration.
  9731. *
  9732. * @param {NodeBuilder} builder - The current node builder.
  9733. * @return {String} The node type.
  9734. */
  9735. getNodeType( builder ) {
  9736. const { returnsNode } = this.getProperties( builder );
  9737. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9738. }
  9739. setup( builder ) {
  9740. // setup properties
  9741. this.getProperties( builder );
  9742. }
  9743. generate( builder ) {
  9744. const properties = this.getProperties( builder );
  9745. const params = this.params;
  9746. const stackNode = properties.stackNode;
  9747. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9748. const param = params[ i ];
  9749. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9750. if ( param.isNode ) {
  9751. type = 'int';
  9752. name = this.getVarName( i );
  9753. start = '0';
  9754. end = param.build( builder, type );
  9755. condition = '<';
  9756. } else {
  9757. type = param.type || 'int';
  9758. name = param.name || this.getVarName( i );
  9759. start = param.start;
  9760. end = param.end;
  9761. condition = param.condition;
  9762. update = param.update;
  9763. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9764. else if ( start && start.isNode ) start = start.build( builder, type );
  9765. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9766. else if ( end && end.isNode ) end = end.build( builder, type );
  9767. if ( start !== undefined && end === undefined ) {
  9768. start = start + ' - 1';
  9769. end = '0';
  9770. condition = '>=';
  9771. } else if ( end !== undefined && start === undefined ) {
  9772. start = '0';
  9773. condition = '<';
  9774. }
  9775. if ( condition === undefined ) {
  9776. if ( Number( start ) > Number( end ) ) {
  9777. condition = '>=';
  9778. } else {
  9779. condition = '<';
  9780. }
  9781. }
  9782. }
  9783. const internalParam = { start, end, condition };
  9784. //
  9785. const startSnippet = internalParam.start;
  9786. const endSnippet = internalParam.end;
  9787. let declarationSnippet = '';
  9788. let conditionalSnippet = '';
  9789. let updateSnippet = '';
  9790. if ( ! update ) {
  9791. if ( type === 'int' || type === 'uint' ) {
  9792. if ( condition.includes( '<' ) ) update = '++';
  9793. else update = '--';
  9794. } else {
  9795. if ( condition.includes( '<' ) ) update = '+= 1.';
  9796. else update = '-= 1.';
  9797. }
  9798. }
  9799. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9800. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9801. updateSnippet += name + ' ' + update;
  9802. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9803. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9804. }
  9805. const stackSnippet = stackNode.build( builder, 'void' );
  9806. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9807. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9808. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9809. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9810. }
  9811. builder.addFlowTab();
  9812. return returnsSnippet;
  9813. }
  9814. }
  9815. /**
  9816. * TSL function for creating a loop node.
  9817. *
  9818. * @function
  9819. * @param {...Any} params - A list of parameters.
  9820. * @returns {LoopNode}
  9821. */
  9822. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9823. /**
  9824. * TSL function for creating a `Continue()` expression.
  9825. *
  9826. * @function
  9827. * @returns {ExpressionNode}
  9828. */
  9829. const Continue = () => expression( 'continue' ).append();
  9830. /**
  9831. * TSL function for creating a `Break()` expression.
  9832. *
  9833. * @function
  9834. * @returns {ExpressionNode}
  9835. */
  9836. const Break = () => expression( 'break' ).append();
  9837. // deprecated
  9838. /**
  9839. * @function
  9840. * @deprecated since r168. Use {@link Loop} instead.
  9841. *
  9842. * @param {...any} params
  9843. * @returns {LoopNode}
  9844. */
  9845. const loop = ( ...params ) => { // @deprecated, r168
  9846. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9847. return Loop( ...params );
  9848. };
  9849. /** @module MorphNode **/
  9850. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9851. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9852. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9853. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9854. const y = texelIndex.div( width );
  9855. const x = texelIndex.sub( y.mul( width ) );
  9856. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9857. return bufferAttrib.mul( influence );
  9858. } );
  9859. function getEntry( geometry ) {
  9860. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9861. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9862. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9863. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9864. // into an array of data textures. Each layer represents a single morph target.
  9865. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9866. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9867. let entry = _morphTextures.get( geometry );
  9868. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9869. if ( entry !== undefined ) entry.texture.dispose();
  9870. const morphTargets = geometry.morphAttributes.position || [];
  9871. const morphNormals = geometry.morphAttributes.normal || [];
  9872. const morphColors = geometry.morphAttributes.color || [];
  9873. let vertexDataCount = 0;
  9874. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9875. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9876. if ( hasMorphColors === true ) vertexDataCount = 3;
  9877. let width = geometry.attributes.position.count * vertexDataCount;
  9878. let height = 1;
  9879. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9880. if ( width > maxTextureSize ) {
  9881. height = Math.ceil( width / maxTextureSize );
  9882. width = maxTextureSize;
  9883. }
  9884. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9885. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9886. bufferTexture.type = FloatType;
  9887. bufferTexture.needsUpdate = true;
  9888. // fill buffer
  9889. const vertexDataStride = vertexDataCount * 4;
  9890. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9891. const morphTarget = morphTargets[ i ];
  9892. const morphNormal = morphNormals[ i ];
  9893. const morphColor = morphColors[ i ];
  9894. const offset = width * height * 4 * i;
  9895. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9896. const stride = j * vertexDataStride;
  9897. if ( hasMorphPosition === true ) {
  9898. _morphVec4.fromBufferAttribute( morphTarget, j );
  9899. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9900. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9901. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9902. buffer[ offset + stride + 3 ] = 0;
  9903. }
  9904. if ( hasMorphNormals === true ) {
  9905. _morphVec4.fromBufferAttribute( morphNormal, j );
  9906. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9907. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9908. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9909. buffer[ offset + stride + 7 ] = 0;
  9910. }
  9911. if ( hasMorphColors === true ) {
  9912. _morphVec4.fromBufferAttribute( morphColor, j );
  9913. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9914. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9915. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9916. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9917. }
  9918. }
  9919. }
  9920. entry = {
  9921. count: morphTargetsCount,
  9922. texture: bufferTexture,
  9923. stride: vertexDataCount,
  9924. size: new Vector2( width, height )
  9925. };
  9926. _morphTextures.set( geometry, entry );
  9927. function disposeTexture() {
  9928. bufferTexture.dispose();
  9929. _morphTextures.delete( geometry );
  9930. geometry.removeEventListener( 'dispose', disposeTexture );
  9931. }
  9932. geometry.addEventListener( 'dispose', disposeTexture );
  9933. }
  9934. return entry;
  9935. }
  9936. /**
  9937. * This node implements the vertex transformation shader logic which is required
  9938. * for morph target animation.
  9939. *
  9940. * @augments Node
  9941. */
  9942. class MorphNode extends Node {
  9943. static get type() {
  9944. return 'MorphNode';
  9945. }
  9946. /**
  9947. * Constructs a new morph node.
  9948. *
  9949. * @param {Mesh} mesh - The mesh holding the morph targets.
  9950. */
  9951. constructor( mesh ) {
  9952. super( 'void' );
  9953. /**
  9954. * The mesh holding the morph targets.
  9955. *
  9956. * @type {Mesh}
  9957. */
  9958. this.mesh = mesh;
  9959. /**
  9960. * A uniform node which represents the morph base influence value.
  9961. *
  9962. * @type {UniformNode<float>}
  9963. */
  9964. this.morphBaseInfluence = uniform( 1 );
  9965. /**
  9966. * The update type overwritten since morph nodes are updated per object.
  9967. *
  9968. * @type {String}
  9969. */
  9970. this.updateType = NodeUpdateType.OBJECT;
  9971. }
  9972. /**
  9973. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9974. *
  9975. * @param {NodeBuilder} builder - The current node builder.
  9976. */
  9977. setup( builder ) {
  9978. const { geometry } = builder;
  9979. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9980. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9981. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9982. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9983. // nodes
  9984. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9985. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9986. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9987. const width = int( size.width );
  9988. Loop( morphTargetsCount, ( { i } ) => {
  9989. const influence = float( 0 ).toVar();
  9990. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9991. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9992. } else {
  9993. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9994. }
  9995. if ( hasMorphPosition === true ) {
  9996. positionLocal.addAssign( getMorph( {
  9997. bufferMap,
  9998. influence,
  9999. stride,
  10000. width,
  10001. depth: i,
  10002. offset: int( 0 )
  10003. } ) );
  10004. }
  10005. if ( hasMorphNormals === true ) {
  10006. normalLocal.addAssign( getMorph( {
  10007. bufferMap,
  10008. influence,
  10009. stride,
  10010. width,
  10011. depth: i,
  10012. offset: int( 1 )
  10013. } ) );
  10014. }
  10015. } );
  10016. }
  10017. /**
  10018. * Updates the state of the morphed mesh by updating the base influence.
  10019. *
  10020. * @param {NodeFrame} frame - The current node frame.
  10021. */
  10022. update( /*frame*/ ) {
  10023. const morphBaseInfluence = this.morphBaseInfluence;
  10024. if ( this.mesh.geometry.morphTargetsRelative ) {
  10025. morphBaseInfluence.value = 1;
  10026. } else {
  10027. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10028. }
  10029. }
  10030. }
  10031. /**
  10032. * TSL function for creating a morph node.
  10033. *
  10034. * @function
  10035. * @param {Mesh} mesh - The mesh holding the morph targets.
  10036. * @returns {MorphNode}
  10037. */
  10038. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10039. /**
  10040. * Base class for lighting nodes.
  10041. *
  10042. * @augments Node
  10043. */
  10044. class LightingNode extends Node {
  10045. static get type() {
  10046. return 'LightingNode';
  10047. }
  10048. /**
  10049. * Constructs a new lighting node.
  10050. */
  10051. constructor() {
  10052. super( 'vec3' );
  10053. /**
  10054. * This flag can be used for type testing.
  10055. *
  10056. * @type {Boolean}
  10057. * @readonly
  10058. * @default true
  10059. */
  10060. this.isLightingNode = true;
  10061. }
  10062. }
  10063. /**
  10064. * A generic class that can be used by nodes which contribute
  10065. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10066. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10067. *
  10068. * @augments LightingNode
  10069. */
  10070. class AONode extends LightingNode {
  10071. static get type() {
  10072. return 'AONode';
  10073. }
  10074. /**
  10075. * Constructs a new AO node.
  10076. *
  10077. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10078. */
  10079. constructor( aoNode = null ) {
  10080. super();
  10081. /**
  10082. * The ambient occlusion node.
  10083. *
  10084. * @type {Node<float>?}
  10085. * @default null
  10086. */
  10087. this.aoNode = aoNode;
  10088. }
  10089. setup( builder ) {
  10090. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10091. }
  10092. }
  10093. /**
  10094. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10095. * by adding lighting specific context data. It represents the runtime context of
  10096. * {@link LightsNode}.
  10097. *
  10098. * @augments ContextNode
  10099. */
  10100. class LightingContextNode extends ContextNode {
  10101. static get type() {
  10102. return 'LightingContextNode';
  10103. }
  10104. /**
  10105. * Constructs a new lighting context node.
  10106. *
  10107. * @param {LightsNode} node - The lights node.
  10108. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10109. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10110. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10111. */
  10112. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10113. super( node );
  10114. /**
  10115. * The current lighting model.
  10116. *
  10117. * @type {LightingModel?}
  10118. * @default null
  10119. */
  10120. this.lightingModel = lightingModel;
  10121. /**
  10122. * A backdrop node.
  10123. *
  10124. * @type {Node<vec3>?}
  10125. * @default null
  10126. */
  10127. this.backdropNode = backdropNode;
  10128. /**
  10129. * A backdrop alpha node.
  10130. *
  10131. * @type {Node<float>?}
  10132. * @default null
  10133. */
  10134. this.backdropAlphaNode = backdropAlphaNode;
  10135. this._value = null;
  10136. }
  10137. /**
  10138. * Returns a lighting context object.
  10139. *
  10140. * @return {{
  10141. * radiance: Node<vec3>,
  10142. * irradiance: Node<vec3>,
  10143. * iblIrradiance: Node<vec3>,
  10144. * ambientOcclusion: Node<float>,
  10145. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10146. * backdrop: Node<vec3>,
  10147. * backdropAlpha: Node<float>
  10148. * }} The lighting context object.
  10149. */
  10150. getContext() {
  10151. const { backdropNode, backdropAlphaNode } = this;
  10152. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10153. directSpecular = vec3().toVar( 'directSpecular' ),
  10154. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10155. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10156. const reflectedLight = {
  10157. directDiffuse,
  10158. directSpecular,
  10159. indirectDiffuse,
  10160. indirectSpecular
  10161. };
  10162. const context = {
  10163. radiance: vec3().toVar( 'radiance' ),
  10164. irradiance: vec3().toVar( 'irradiance' ),
  10165. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10166. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10167. reflectedLight,
  10168. backdrop: backdropNode,
  10169. backdropAlpha: backdropAlphaNode
  10170. };
  10171. return context;
  10172. }
  10173. setup( builder ) {
  10174. this.value = this._value || ( this._value = this.getContext() );
  10175. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10176. return super.setup( builder );
  10177. }
  10178. }
  10179. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10180. /**
  10181. * A generic class that can be used by nodes which contribute
  10182. * irradiance to the scene. E.g. a light map node can be used
  10183. * as input for this module. Used in {@link NodeMaterial}.
  10184. *
  10185. * @augments LightingNode
  10186. */
  10187. class IrradianceNode extends LightingNode {
  10188. static get type() {
  10189. return 'IrradianceNode';
  10190. }
  10191. /**
  10192. * Constructs a new irradiance node.
  10193. *
  10194. * @param {Node<vec3>} node - A node contributing irradiance.
  10195. */
  10196. constructor( node ) {
  10197. super();
  10198. /**
  10199. * A node contributing irradiance.
  10200. *
  10201. * @type {Node<vec3>}
  10202. */
  10203. this.node = node;
  10204. }
  10205. setup( builder ) {
  10206. builder.context.irradiance.addAssign( this.node );
  10207. }
  10208. }
  10209. /** @module ScreenNode **/
  10210. let screenSizeVec, viewportVec;
  10211. /**
  10212. * This node provides a collection of screen related metrics.
  10213. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10214. * resolution or viewport data as well as fragment or uv coordinates.
  10215. *
  10216. * @augments Node
  10217. */
  10218. class ScreenNode extends Node {
  10219. static get type() {
  10220. return 'ScreenNode';
  10221. }
  10222. /**
  10223. * Constructs a new screen node.
  10224. *
  10225. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10226. */
  10227. constructor( scope ) {
  10228. super();
  10229. /**
  10230. * The node represents different metric depending on which scope is selected.
  10231. *
  10232. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10233. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10234. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10235. * - `ScreenNode.UV`: Normalized coordinates.
  10236. *
  10237. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10238. */
  10239. this.scope = scope;
  10240. /**
  10241. * This flag can be used for type testing.
  10242. *
  10243. * @type {Boolean}
  10244. * @readonly
  10245. * @default true
  10246. */
  10247. this.isViewportNode = true;
  10248. }
  10249. /**
  10250. * This method is overwritten since the node type depends on the selected scope.
  10251. *
  10252. * @return {('vec2'|'vec4')} The node type.
  10253. */
  10254. getNodeType() {
  10255. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10256. else return 'vec2';
  10257. }
  10258. /**
  10259. * This method is overwritten since the node's update type depends on the selected scope.
  10260. *
  10261. * @return {NodeUpdateType} The update type.
  10262. */
  10263. getUpdateType() {
  10264. let updateType = NodeUpdateType.NONE;
  10265. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10266. updateType = NodeUpdateType.RENDER;
  10267. }
  10268. this.updateType = updateType;
  10269. return updateType;
  10270. }
  10271. /**
  10272. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10273. * from the current renderer.
  10274. *
  10275. * @param {NodeFrame} frame - A reference to the current node frame.
  10276. */
  10277. update( { renderer } ) {
  10278. const renderTarget = renderer.getRenderTarget();
  10279. if ( this.scope === ScreenNode.VIEWPORT ) {
  10280. if ( renderTarget !== null ) {
  10281. viewportVec.copy( renderTarget.viewport );
  10282. } else {
  10283. renderer.getViewport( viewportVec );
  10284. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10285. }
  10286. } else {
  10287. if ( renderTarget !== null ) {
  10288. screenSizeVec.width = renderTarget.width;
  10289. screenSizeVec.height = renderTarget.height;
  10290. } else {
  10291. renderer.getDrawingBufferSize( screenSizeVec );
  10292. }
  10293. }
  10294. }
  10295. setup( /*builder*/ ) {
  10296. const scope = this.scope;
  10297. let output = null;
  10298. if ( scope === ScreenNode.SIZE ) {
  10299. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10300. } else if ( scope === ScreenNode.VIEWPORT ) {
  10301. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10302. } else {
  10303. output = vec2( screenCoordinate.div( screenSize ) );
  10304. }
  10305. return output;
  10306. }
  10307. generate( builder ) {
  10308. if ( this.scope === ScreenNode.COORDINATE ) {
  10309. let coord = builder.getFragCoord();
  10310. if ( builder.isFlipY() ) {
  10311. // follow webgpu standards
  10312. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10313. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10314. }
  10315. return coord;
  10316. }
  10317. return super.generate( builder );
  10318. }
  10319. }
  10320. ScreenNode.COORDINATE = 'coordinate';
  10321. ScreenNode.VIEWPORT = 'viewport';
  10322. ScreenNode.SIZE = 'size';
  10323. ScreenNode.UV = 'uv';
  10324. // Screen
  10325. /**
  10326. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10327. *
  10328. * @type {ScreenNode<vec2>}
  10329. */
  10330. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10331. /**
  10332. * TSL object that represents the screen resolution in physical pixel units.
  10333. *
  10334. * @type {ScreenNode<vec2>}
  10335. */
  10336. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10337. /**
  10338. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10339. *
  10340. * @type {ScreenNode<vec2>}
  10341. */
  10342. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10343. // Viewport
  10344. /**
  10345. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10346. *
  10347. * @type {ScreenNode<vec4>}
  10348. */
  10349. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10350. /**
  10351. * TSL object that represents the viewport resolution in physical pixel units.
  10352. *
  10353. * @type {ScreenNode<vec2>}
  10354. */
  10355. const viewportSize = viewport.zw;
  10356. /**
  10357. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10358. *
  10359. * @type {ScreenNode<vec2>}
  10360. */
  10361. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10362. /**
  10363. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10364. *
  10365. * @type {ScreenNode<vec2>}
  10366. */
  10367. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10368. // Deprecated
  10369. /**
  10370. * @deprecated since r169. Use {@link screenSize} instead.
  10371. */
  10372. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10373. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10374. return screenSize;
  10375. }, 'vec2' ).once() )();
  10376. /**
  10377. * @deprecated since r168. Use {@link screenUV} instead.
  10378. */
  10379. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10380. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10381. return screenUV;
  10382. }, 'vec2' ).once() )();
  10383. /**
  10384. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10385. */
  10386. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10387. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10388. return screenUV.flipY();
  10389. }, 'vec2' ).once() )();
  10390. /** @module ViewportTextureNode **/
  10391. const _size$4 = /*@__PURE__*/ new Vector2();
  10392. /**
  10393. * A special type of texture node which represents the data of the current viewport
  10394. * as a texture. The module extracts data from the current bound framebuffer with
  10395. * a copy operation so no extra render pass is required to produce the texture data
  10396. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10397. * variety of effects like refractive or transmissive materials.
  10398. *
  10399. * @augments module:TextureNode~TextureNode
  10400. */
  10401. class ViewportTextureNode extends TextureNode {
  10402. static get type() {
  10403. return 'ViewportTextureNode';
  10404. }
  10405. /**
  10406. * Constructs a new viewport texture node.
  10407. *
  10408. * @param {Node} [uvNode=screenUV] - The uv node.
  10409. * @param {Node?} [levelNode=null] - The level node.
  10410. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10411. */
  10412. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10413. if ( framebufferTexture === null ) {
  10414. framebufferTexture = new FramebufferTexture();
  10415. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10416. }
  10417. super( framebufferTexture, uvNode, levelNode );
  10418. /**
  10419. * Whether to generate mipmaps or not.
  10420. *
  10421. * @type {Boolean}
  10422. * @default false
  10423. */
  10424. this.generateMipmaps = false;
  10425. /**
  10426. * This flag can be used for type testing.
  10427. *
  10428. * @type {Boolean}
  10429. * @readonly
  10430. * @default true
  10431. */
  10432. this.isOutputTextureNode = true;
  10433. /**
  10434. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10435. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10436. *
  10437. * @type {String}
  10438. * @default 'frame'
  10439. */
  10440. this.updateBeforeType = NodeUpdateType.FRAME;
  10441. }
  10442. updateBefore( frame ) {
  10443. const renderer = frame.renderer;
  10444. renderer.getDrawingBufferSize( _size$4 );
  10445. //
  10446. const framebufferTexture = this.value;
  10447. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10448. framebufferTexture.image.width = _size$4.width;
  10449. framebufferTexture.image.height = _size$4.height;
  10450. framebufferTexture.needsUpdate = true;
  10451. }
  10452. //
  10453. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10454. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10455. renderer.copyFramebufferToTexture( framebufferTexture );
  10456. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10457. }
  10458. clone() {
  10459. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10460. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10461. return viewportTextureNode;
  10462. }
  10463. }
  10464. /**
  10465. * TSL function for creating a viewport texture node.
  10466. *
  10467. * @function
  10468. * @param {Node} [uvNode=screenUV] - The uv node.
  10469. * @param {Node?} [levelNode=null] - The level node.
  10470. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10471. * @returns {ViewportTextureNode}
  10472. */
  10473. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10474. /**
  10475. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10476. *
  10477. * @function
  10478. * @param {Node} [uvNode=screenUV] - The uv node.
  10479. * @param {Node?} [levelNode=null] - The level node.
  10480. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10481. * @returns {ViewportTextureNode}
  10482. */
  10483. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10484. /** @module ViewportDepthTextureNode **/
  10485. let sharedDepthbuffer = null;
  10486. /**
  10487. * Represents the depth of the current viewport as a texture. This module
  10488. * can be used in combination with viewport texture to achieve effects
  10489. * that require depth evaluation.
  10490. *
  10491. * @augments module:ViewportTextureNode~ViewportTextureNode
  10492. */
  10493. class ViewportDepthTextureNode extends ViewportTextureNode {
  10494. static get type() {
  10495. return 'ViewportDepthTextureNode';
  10496. }
  10497. /**
  10498. * Constructs a new viewport depth texture node.
  10499. *
  10500. * @param {Node} [uvNode=screenUV] - The uv node.
  10501. * @param {Node?} [levelNode=null] - The level node.
  10502. */
  10503. constructor( uvNode = screenUV, levelNode = null ) {
  10504. if ( sharedDepthbuffer === null ) {
  10505. sharedDepthbuffer = new DepthTexture();
  10506. }
  10507. super( uvNode, levelNode, sharedDepthbuffer );
  10508. }
  10509. }
  10510. /**
  10511. * TSL function for a viewport depth texture node.
  10512. *
  10513. * @function
  10514. * @param {Node} [uvNode=screenUV] - The uv node.
  10515. * @param {Node?} [levelNode=null] - The level node.
  10516. * @returns {ViewportDepthTextureNode}
  10517. */
  10518. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10519. /** @module ViewportDepthNode **/
  10520. /**
  10521. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10522. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10523. * fragment or for depth evaluation purposes.
  10524. *
  10525. * @augments Node
  10526. */
  10527. class ViewportDepthNode extends Node {
  10528. static get type() {
  10529. return 'ViewportDepthNode';
  10530. }
  10531. /**
  10532. * Constructs a new viewport depth node.
  10533. *
  10534. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10535. * @param {Node?} [valueNode=null] - The value node.
  10536. */
  10537. constructor( scope, valueNode = null ) {
  10538. super( 'float' );
  10539. /**
  10540. * The node behaves differently depending on which scope is selected.
  10541. *
  10542. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10543. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10544. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10545. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10546. *
  10547. * @type {('depth'|'depthBase'|'linearDepth')}
  10548. */
  10549. this.scope = scope;
  10550. /**
  10551. * Can be used to define a custom depth value.
  10552. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10553. *
  10554. * @type {Node?}
  10555. * @default null
  10556. */
  10557. this.valueNode = valueNode;
  10558. /**
  10559. * This flag can be used for type testing.
  10560. *
  10561. * @type {Boolean}
  10562. * @readonly
  10563. * @default true
  10564. */
  10565. this.isViewportDepthNode = true;
  10566. }
  10567. generate( builder ) {
  10568. const { scope } = this;
  10569. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10570. return builder.getFragDepth();
  10571. }
  10572. return super.generate( builder );
  10573. }
  10574. setup( { camera } ) {
  10575. const { scope } = this;
  10576. const value = this.valueNode;
  10577. let node = null;
  10578. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10579. if ( value !== null ) {
  10580. node = depthBase().assign( value );
  10581. }
  10582. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10583. if ( camera.isPerspectiveCamera ) {
  10584. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10585. } else {
  10586. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10587. }
  10588. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10589. if ( value !== null ) {
  10590. if ( camera.isPerspectiveCamera ) {
  10591. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10592. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10593. } else {
  10594. node = value;
  10595. }
  10596. } else {
  10597. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10598. }
  10599. }
  10600. return node;
  10601. }
  10602. }
  10603. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10604. ViewportDepthNode.DEPTH = 'depth';
  10605. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10606. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10607. /**
  10608. * TSL function for converting a viewZ value to an orthographic depth value.
  10609. *
  10610. * @function
  10611. * @param {Node<float>} viewZ - The viewZ node.
  10612. * @param {Node<float>} near - The camera's near value.
  10613. * @param {Node<float>} far - The camera's far value.
  10614. * @returns {Node<float>}
  10615. */
  10616. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10617. /**
  10618. * TSL function for converting an orthographic depth value to a viewZ value.
  10619. *
  10620. * @function
  10621. * @param {Node<float>} depth - The orthographic depth.
  10622. * @param {Node<float>} near - The camera's near value.
  10623. * @param {Node<float>} far - The camera's far value.
  10624. * @returns {Node<float>}
  10625. */
  10626. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10627. /**
  10628. * TSL function for converting a viewZ value to a perspective depth value.
  10629. *
  10630. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10631. *
  10632. * @function
  10633. * @param {Node<float>} viewZ - The viewZ node.
  10634. * @param {Node<float>} near - The camera's near value.
  10635. * @param {Node<float>} far - The camera's far value.
  10636. * @returns {Node<float>}
  10637. */
  10638. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10639. /**
  10640. * TSL function for converting a perspective depth value to a viewZ value.
  10641. *
  10642. * @function
  10643. * @param {Node<float>} depth - The perspective depth.
  10644. * @param {Node<float>} near - The camera's near value.
  10645. * @param {Node<float>} far - The camera's far value.
  10646. * @returns {Node<float>}
  10647. */
  10648. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10649. /**
  10650. * TSL function for converting a viewZ value to a logarithmic depth value.
  10651. *
  10652. * @function
  10653. * @param {Node<float>} viewZ - The viewZ node.
  10654. * @param {Node<float>} near - The camera's near value.
  10655. * @param {Node<float>} far - The camera's far value.
  10656. * @returns {Node<float>}
  10657. */
  10658. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10659. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10660. // The final logarithmic depth formula used here is adapted from one described in an
  10661. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10662. // which was an improvement upon an earlier formula one described in an
  10663. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10664. // Ulrich's formula is the following:
  10665. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10666. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10667. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10668. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10669. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10670. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10671. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10672. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10673. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10674. // Outerra eventually made another improvement to their original "C-constant" variant,
  10675. // but it still does not incorporate the camera near plane (for this version,
  10676. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10677. // Here we make 4 changes to Ulrich's formula:
  10678. // 1. Clamp the camera near plane so we don't divide by 0.
  10679. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10680. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10681. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10682. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10683. // so we do the same here, hence the 'viewZ.negate()' call.
  10684. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10685. near = near.max( 1e-6 ).toVar();
  10686. const numerator = log2( viewZ.negate().div( near ) );
  10687. const denominator = log2( far.div( near ) );
  10688. return numerator.div( denominator );
  10689. };
  10690. /**
  10691. * TSL function for converting a logarithmic depth value to a viewZ value.
  10692. *
  10693. * @function
  10694. * @param {Node<float>} depth - The logarithmic depth.
  10695. * @param {Node<float>} near - The camera's near value.
  10696. * @param {Node<float>} far - The camera's far value.
  10697. * @returns {Node<float>}
  10698. */
  10699. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10700. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10701. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10702. // a negative viewZ).
  10703. const exponent = depth.mul( log( far.div( near ) ) );
  10704. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10705. };
  10706. /**
  10707. * TSL function for defining a value for the current fragment's depth.
  10708. *
  10709. * @function
  10710. * @param {Node<float>} value - The depth value to set.
  10711. * @returns {ViewportDepthNode<float>}
  10712. */
  10713. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10714. /**
  10715. * TSL object that represents the depth value for the current fragment.
  10716. *
  10717. * @type {ViewportDepthNode}
  10718. */
  10719. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10720. /**
  10721. * TSL function for converting a perspective depth value to linear depth.
  10722. *
  10723. * @function
  10724. * @param {Node<float>} value - The perspective depth.
  10725. * @returns {ViewportDepthNode<float>}
  10726. */
  10727. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10728. /**
  10729. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10730. *
  10731. * @type {ViewportDepthNode}
  10732. */
  10733. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10734. depth.assign = ( value ) => depthBase( value );
  10735. /** @module BuiltinNode **/
  10736. /**
  10737. * The node allows to set values for built-in shader variables. That is
  10738. * required for features like hardware-accelerated vertex clipping.
  10739. *
  10740. * @augments Node
  10741. */
  10742. class BuiltinNode extends Node {
  10743. /**
  10744. * Constructs a new builtin node.
  10745. *
  10746. * @param {String} name - The name of the built-in shader variable.
  10747. */
  10748. constructor( name ) {
  10749. super( 'float' );
  10750. /**
  10751. * The name of the built-in shader variable.
  10752. *
  10753. * @type {String}
  10754. */
  10755. this.name = name;
  10756. /**
  10757. * This flag can be used for type testing.
  10758. *
  10759. * @type {Boolean}
  10760. * @readonly
  10761. * @default true
  10762. */
  10763. this.isBuiltinNode = true;
  10764. }
  10765. /**
  10766. * Generates the code snippet of the builtin node.
  10767. *
  10768. * @param {NodeBuilder} builder - The current node builder.
  10769. * @return {String} The generated code snippet.
  10770. */
  10771. generate( /* builder */ ) {
  10772. return this.name;
  10773. }
  10774. }
  10775. /**
  10776. * TSL function for creating a builtin node.
  10777. *
  10778. * @function
  10779. * @param {String} name - The name of the built-in shader variable.
  10780. * @returns {BuiltinNode}
  10781. */
  10782. const builtin = nodeProxy( BuiltinNode );
  10783. /** @module ClippingNode **/
  10784. /**
  10785. * ```
  10786. * This node is used in {@link NodeMaterial} to setup the clipping
  10787. * which can happen hardware-accelerated (if supported) and optionally
  10788. * use alpha-to-coverage for anti-aliasing clipped edges.
  10789. * ```
  10790. * @augments Node
  10791. */
  10792. class ClippingNode extends Node {
  10793. static get type() {
  10794. return 'ClippingNode';
  10795. }
  10796. /**
  10797. * Constructs a new clipping node.
  10798. *
  10799. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10800. * the selected scope influences the behavior of the node and what type of code is generated.
  10801. */
  10802. constructor( scope = ClippingNode.DEFAULT ) {
  10803. super();
  10804. /**
  10805. * The node's scope. Similar to other nodes, the selected scope influences
  10806. * the behavior of the node and what type of code is generated.
  10807. *
  10808. * @type {('default'|'hardware'|'alphaToCoverage')}
  10809. */
  10810. this.scope = scope;
  10811. }
  10812. /**
  10813. * Setups the node depending on the selected scope.
  10814. *
  10815. * @param {NodeBuilder} builder - The current node builder.
  10816. * @return {Node} The result node.
  10817. */
  10818. setup( builder ) {
  10819. super.setup( builder );
  10820. const clippingContext = builder.clippingContext;
  10821. const { intersectionPlanes, unionPlanes } = clippingContext;
  10822. this.hardwareClipping = builder.material.hardwareClipping;
  10823. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10824. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10825. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10826. return this.setupHardwareClipping( unionPlanes, builder );
  10827. } else {
  10828. return this.setupDefault( intersectionPlanes, unionPlanes );
  10829. }
  10830. }
  10831. /**
  10832. * Setups alpha to coverage.
  10833. *
  10834. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10835. * @param {Array<Vector4>} unionPlanes - The union planes.
  10836. * @return {Node} The result node.
  10837. */
  10838. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10839. return Fn( () => {
  10840. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10841. const distanceGradient = float().toVar( 'distanceToGradient' );
  10842. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10843. const numUnionPlanes = unionPlanes.length;
  10844. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10845. const clippingPlanes = uniformArray( unionPlanes );
  10846. Loop( numUnionPlanes, ( { i } ) => {
  10847. const plane = clippingPlanes.element( i );
  10848. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10849. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10850. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10851. } );
  10852. }
  10853. const numIntersectionPlanes = intersectionPlanes.length;
  10854. if ( numIntersectionPlanes > 0 ) {
  10855. const clippingPlanes = uniformArray( intersectionPlanes );
  10856. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10857. Loop( numIntersectionPlanes, ( { i } ) => {
  10858. const plane = clippingPlanes.element( i );
  10859. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10860. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10861. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10862. } );
  10863. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10864. }
  10865. diffuseColor.a.mulAssign( clipOpacity );
  10866. diffuseColor.a.equal( 0.0 ).discard();
  10867. } )();
  10868. }
  10869. /**
  10870. * Setups the default clipping.
  10871. *
  10872. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10873. * @param {Array<Vector4>} unionPlanes - The union planes.
  10874. * @return {Node} The result node.
  10875. */
  10876. setupDefault( intersectionPlanes, unionPlanes ) {
  10877. return Fn( () => {
  10878. const numUnionPlanes = unionPlanes.length;
  10879. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10880. const clippingPlanes = uniformArray( unionPlanes );
  10881. Loop( numUnionPlanes, ( { i } ) => {
  10882. const plane = clippingPlanes.element( i );
  10883. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10884. } );
  10885. }
  10886. const numIntersectionPlanes = intersectionPlanes.length;
  10887. if ( numIntersectionPlanes > 0 ) {
  10888. const clippingPlanes = uniformArray( intersectionPlanes );
  10889. const clipped = bool( true ).toVar( 'clipped' );
  10890. Loop( numIntersectionPlanes, ( { i } ) => {
  10891. const plane = clippingPlanes.element( i );
  10892. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10893. } );
  10894. clipped.discard();
  10895. }
  10896. } )();
  10897. }
  10898. /**
  10899. * Setups hardware clipping.
  10900. *
  10901. * @param {Array<Vector4>} unionPlanes - The union planes.
  10902. * @param {NodeBuilder} builder - The current node builder.
  10903. * @return {Node} The result node.
  10904. */
  10905. setupHardwareClipping( unionPlanes, builder ) {
  10906. const numUnionPlanes = unionPlanes.length;
  10907. builder.enableHardwareClipping( numUnionPlanes );
  10908. return Fn( () => {
  10909. const clippingPlanes = uniformArray( unionPlanes );
  10910. const hw_clip_distances = builtin( builder.getClipDistance() );
  10911. Loop( numUnionPlanes, ( { i } ) => {
  10912. const plane = clippingPlanes.element( i );
  10913. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10914. hw_clip_distances.element( i ).assign( distance );
  10915. } );
  10916. } )();
  10917. }
  10918. }
  10919. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10920. ClippingNode.DEFAULT = 'default';
  10921. ClippingNode.HARDWARE = 'hardware';
  10922. /**
  10923. * TSL function for setting up the default clipping logic.
  10924. *
  10925. * @function
  10926. * @returns {ClippingNode}
  10927. */
  10928. const clipping = () => nodeObject( new ClippingNode() );
  10929. /**
  10930. * TSL function for setting up alpha to coverage.
  10931. *
  10932. * @function
  10933. * @returns {ClippingNode}
  10934. */
  10935. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10936. /**
  10937. * TSL function for setting up hardware-based clipping.
  10938. *
  10939. * @function
  10940. * @returns {ClippingNode}
  10941. */
  10942. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10943. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10944. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10945. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10946. 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 ) ) ) ) ) );
  10947. } );
  10948. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10949. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10950. } );
  10951. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10952. // Find the discretized derivatives of our coordinates
  10953. const maxDeriv = max$1(
  10954. length( dFdx( position.xyz ) ),
  10955. length( dFdy( position.xyz ) )
  10956. );
  10957. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10958. // Find two nearest log-discretized noise scales
  10959. const pixScales = vec2(
  10960. exp2( floor( log2( pixScale ) ) ),
  10961. exp2( ceil( log2( pixScale ) ) )
  10962. );
  10963. // Compute alpha thresholds at our two noise scales
  10964. const alpha = vec2(
  10965. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10966. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10967. );
  10968. // Factor to interpolate lerp with
  10969. const lerpFactor = fract( log2( pixScale ) );
  10970. // Interpolate alpha threshold from noise at two scales
  10971. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10972. // Pass into CDF to compute uniformly distrib threshold
  10973. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10974. const cases = vec3(
  10975. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10976. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10977. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10978. // Find our final, uniformly distributed alpha threshold (ατ)
  10979. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10980. // Avoids ατ == 0. Could also do ατ =1-ατ
  10981. return clamp( threshold, 1.0e-6, 1.0 );
  10982. } ).setLayout( {
  10983. name: 'getAlphaHashThreshold',
  10984. type: 'float',
  10985. inputs: [
  10986. { name: 'position', type: 'vec3' }
  10987. ]
  10988. } );
  10989. /**
  10990. * Base class for all node materials.
  10991. *
  10992. * @augments Material
  10993. */
  10994. class NodeMaterial extends Material {
  10995. static get type() {
  10996. return 'NodeMaterial';
  10997. }
  10998. /**
  10999. * Represents the type of the node material.
  11000. *
  11001. * @type {String}
  11002. */
  11003. get type() {
  11004. return this.constructor.type;
  11005. }
  11006. set type( _value ) { /* */ }
  11007. /**
  11008. * Constructs a new node material.
  11009. */
  11010. constructor() {
  11011. super();
  11012. /**
  11013. * This flag can be used for type testing.
  11014. *
  11015. * @type {Boolean}
  11016. * @readonly
  11017. * @default true
  11018. */
  11019. this.isNodeMaterial = true;
  11020. /**
  11021. * Whether this material is affected by fog or not.
  11022. *
  11023. * @type {Boolean}
  11024. * @default true
  11025. */
  11026. this.fog = true;
  11027. /**
  11028. * Whether this material is affected by lights or not.
  11029. *
  11030. * @type {Boolean}
  11031. * @default false
  11032. */
  11033. this.lights = false;
  11034. /**
  11035. * Whether this material uses hardware clipping or not.
  11036. * This property is managed by the engine and should not be
  11037. * modified by apps.
  11038. *
  11039. * @type {Boolean}
  11040. * @default false
  11041. */
  11042. this.hardwareClipping = false;
  11043. /**
  11044. * Node materials which set their `lights` property to `true`
  11045. * are affected by all lights of the scene. Sometimes selective
  11046. * lighting is wanted which means only _some_ lights in the scene
  11047. * affect a material. This can be achieved by creating an instance
  11048. * of {@link module:LightsNode~LightsNode} with a list of selective
  11049. * lights and assign the node to this property.
  11050. *
  11051. * ```js
  11052. * const customLightsNode = lights( [ light1, light2 ] );
  11053. * material.lightsNode = customLightsNode;
  11054. * ```
  11055. *
  11056. * @type {LightsNode?}
  11057. * @default null
  11058. */
  11059. this.lightsNode = null;
  11060. /**
  11061. * The environment of node materials can be defined by an environment
  11062. * map assigned to the `envMap` property or by `Scene.environment`
  11063. * if the node material is a PBR material. This node property allows to overwrite
  11064. * the default behavior and define the environment with a custom node.
  11065. *
  11066. * ```js
  11067. * material.envNode = pmremTexture( renderTarget.texture );
  11068. * ```
  11069. *
  11070. * @type {Node<vec3>?}
  11071. * @default null
  11072. */
  11073. this.envNode = null;
  11074. /**
  11075. * The lighting of node materials might be influenced by ambient occlusion.
  11076. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11077. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11078. * the default and define the ambient occlusion with a custom node instead.
  11079. *
  11080. * If you don't want to overwrite the diffuse color but modify the existing
  11081. * values instead, use {@link module:MaterialNode.materialAO}.
  11082. *
  11083. * @type {Node<float>?}
  11084. * @default null
  11085. */
  11086. this.aoNode = null;
  11087. /**
  11088. * The diffuse color of node materials is by default inferred from the
  11089. * `color` and `map` properties. This node property allows to overwrite the default
  11090. * and define the diffuse color with a node instead.
  11091. *
  11092. * ```js
  11093. * material.colorNode = color( 0xff0000 ); // define red color
  11094. * ```
  11095. *
  11096. * If you don't want to overwrite the diffuse color but modify the existing
  11097. * values instead, use {@link module:MaterialNode.materialColor}.
  11098. *
  11099. * ```js
  11100. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11101. * ```
  11102. *
  11103. * @type {Node<vec3>?}
  11104. * @default null
  11105. */
  11106. this.colorNode = null;
  11107. /**
  11108. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11109. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11110. * and define the normals with a node instead.
  11111. *
  11112. * If you don't want to overwrite the normals but modify the existing values instead,
  11113. * use {@link module:MaterialNode.materialNormal}.
  11114. *
  11115. * @type {Node<vec3>?}
  11116. * @default null
  11117. */
  11118. this.normalNode = null;
  11119. /**
  11120. * The opacity of node materials is by default inferred from the `opacity`
  11121. * and `alphaMap` properties. This node property allows to overwrite the default
  11122. * and define the opacity with a node instead.
  11123. *
  11124. * If you don't want to overwrite the normals but modify the existing
  11125. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11126. *
  11127. * @type {Node<float>?}
  11128. * @default null
  11129. */
  11130. this.opacityNode = null;
  11131. /**
  11132. * This node can be used to to implement a variety of filter-like effects. The idea is
  11133. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11134. * to create an arbitrary effect and then assign the node composition to this property.
  11135. * Everything behind the object using this material will now be affected by a filter.
  11136. *
  11137. * ```js
  11138. * const material = new NodeMaterial()
  11139. * material.transparent = true;
  11140. *
  11141. * // everything behind the object will be monochromatic
  11142. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11143. * ```
  11144. *
  11145. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11146. *
  11147. * @type {Node<vec3>?}
  11148. * @default null
  11149. */
  11150. this.backdropNode = null;
  11151. /**
  11152. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11153. *
  11154. * @type {Node<float>?}
  11155. * @default null
  11156. */
  11157. this.backdropAlphaNode = null;
  11158. /**
  11159. * The alpha test of node materials is by default inferred from the `alphaTest`
  11160. * property. This node property allows to overwrite the default and define the
  11161. * alpha test with a node instead.
  11162. *
  11163. * If you don't want to overwrite the alpha test but modify the existing
  11164. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11165. *
  11166. * @type {Node<float>?}
  11167. * @default null
  11168. */
  11169. this.alphaTestNode = null;
  11170. /**
  11171. * The local vertex positions are computed based on multiple factors like the
  11172. * attribute data, morphing or skinning. This node property allows to overwrite
  11173. * the default and define local vertex positions with nodes instead.
  11174. *
  11175. * If you don't want to overwrite the vertex positions but modify the existing
  11176. * values instead, use {@link module:Position.positionLocal}.
  11177. *
  11178. *```js
  11179. * material.positionNode = positionLocal.add( displace );
  11180. * ```
  11181. *
  11182. * @type {Node<vec3>?}
  11183. * @default null
  11184. */
  11185. this.positionNode = null;
  11186. /**
  11187. * This node property is intended for logic which modifies geometry data once or per animation step.
  11188. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11189. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11190. * can be implemented.
  11191. *
  11192. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11193. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11194. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11195. * eventually assigned to `geometryNode`.
  11196. *
  11197. * @type {Function}
  11198. * @default null
  11199. */
  11200. this.geometryNode = null;
  11201. /**
  11202. * Allows to overwrite depth values in the fragment shader.
  11203. *
  11204. * @type {Node<float>?}
  11205. * @default null
  11206. */
  11207. this.depthNode = null;
  11208. /**
  11209. * Allows to overwrite the position used for shadow map rendering which
  11210. * is by default {@link module:Position.positionWorld}, the vertex position
  11211. * in world space.
  11212. *
  11213. * @type {Node<float>?}
  11214. * @default null
  11215. */
  11216. this.shadowPositionNode = null;
  11217. /**
  11218. * This node can be used to influence how an object using this node material
  11219. * receive shadows.
  11220. *
  11221. * ```js
  11222. * const totalShadows = float( 1 ).toVar();
  11223. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11224. * totalShadows.mulAssign( shadow );
  11225. * //return float( 1 ); // bypass received shadows
  11226. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11227. * } );
  11228. *
  11229. * @type {Node<vec4>?}
  11230. * @default null
  11231. */
  11232. this.receivedShadowNode = null;
  11233. /**
  11234. * This node can be used to influence how an object using this node material
  11235. * casts shadows. To apply a color to shadows, you can simply do:
  11236. *
  11237. * ```js
  11238. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11239. * ```
  11240. *
  11241. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11242. * is also common to use the property with `Fn` function so checks are performed
  11243. * per fragment.
  11244. *
  11245. * ```js
  11246. * materialCustomShadow.castShadowNode = Fn( () => {
  11247. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11248. * return materialColor;
  11249. * } )();
  11250. * ```
  11251. *
  11252. * @type {Node<vec4>?}
  11253. * @default null
  11254. */
  11255. this.castShadowNode = null;
  11256. /**
  11257. * This node can be used to define the final output of the material.
  11258. *
  11259. * TODO: Explain the differences to `fragmentNode`.
  11260. *
  11261. * @type {Node<vec4>?}
  11262. * @default null
  11263. */
  11264. this.outputNode = null;
  11265. /**
  11266. * MRT configuration is done on renderer or pass level. This node allows to
  11267. * overwrite what values are written into MRT targets on material level. This
  11268. * can be useful for implementing selective FX features that should only affect
  11269. * specific objects.
  11270. *
  11271. * @type {MRTNode?}
  11272. * @default null
  11273. */
  11274. this.mrtNode = null;
  11275. /**
  11276. * This node property can be used if you need complete freedom in implementing
  11277. * the fragment shader. Assigning a node will replace the built-in material
  11278. * logic used in the fragment stage.
  11279. *
  11280. * @type {Node<vec4>?}
  11281. * @default null
  11282. */
  11283. this.fragmentNode = null;
  11284. /**
  11285. * This node property can be used if you need complete freedom in implementing
  11286. * the vertex shader. Assigning a node will replace the built-in material logic
  11287. * used in the vertex stage.
  11288. *
  11289. * @type {Node<vec4>?}
  11290. * @default null
  11291. */
  11292. this.vertexNode = null;
  11293. }
  11294. /**
  11295. * Allows to define a custom cache key that influence the material key computation
  11296. * for render objects.
  11297. *
  11298. * @return {String} The custom cache key.
  11299. */
  11300. customProgramCacheKey() {
  11301. return this.type + getCacheKey$1( this );
  11302. }
  11303. /**
  11304. * Builds this material with the given node builder.
  11305. *
  11306. * @param {NodeBuilder} builder - The current node builder.
  11307. */
  11308. build( builder ) {
  11309. this.setup( builder );
  11310. }
  11311. /**
  11312. * Setups a node material observer with the given builder.
  11313. *
  11314. * @param {NodeBuilder} builder - The current node builder.
  11315. * @return {NodeMaterialObserver} The node material observer.
  11316. */
  11317. setupObserver( builder ) {
  11318. return new NodeMaterialObserver( builder );
  11319. }
  11320. /**
  11321. * Setups the vertex and fragment stage of this node material.
  11322. *
  11323. * @param {NodeBuilder} builder - The current node builder.
  11324. */
  11325. setup( builder ) {
  11326. builder.context.setupNormal = () => this.setupNormal( builder );
  11327. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11328. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11329. const renderer = builder.renderer;
  11330. const renderTarget = renderer.getRenderTarget();
  11331. // < VERTEX STAGE >
  11332. builder.addStack();
  11333. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11334. builder.stack.outputNode = vertexNode;
  11335. this.setupHardwareClipping( builder );
  11336. if ( this.geometryNode !== null ) {
  11337. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11338. }
  11339. builder.addFlow( 'vertex', builder.removeStack() );
  11340. // < FRAGMENT STAGE >
  11341. builder.addStack();
  11342. let resultNode;
  11343. const clippingNode = this.setupClipping( builder );
  11344. if ( this.depthWrite === true || this.depthTest === true ) {
  11345. // only write depth if depth buffer is configured
  11346. if ( renderTarget !== null ) {
  11347. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11348. } else {
  11349. if ( renderer.depth === true ) this.setupDepth( builder );
  11350. }
  11351. }
  11352. if ( this.fragmentNode === null ) {
  11353. this.setupDiffuseColor( builder );
  11354. this.setupVariants( builder );
  11355. const outgoingLightNode = this.setupLighting( builder );
  11356. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11357. // force unsigned floats - useful for RenderTargets
  11358. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11359. resultNode = this.setupOutput( builder, basicOutput );
  11360. // OUTPUT NODE
  11361. output.assign( resultNode );
  11362. //
  11363. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11364. // MRT
  11365. if ( renderTarget !== null ) {
  11366. const mrt = renderer.getMRT();
  11367. const materialMRT = this.mrtNode;
  11368. if ( mrt !== null ) {
  11369. resultNode = mrt;
  11370. if ( materialMRT !== null ) {
  11371. resultNode = mrt.merge( materialMRT );
  11372. }
  11373. } else if ( materialMRT !== null ) {
  11374. resultNode = materialMRT;
  11375. }
  11376. }
  11377. } else {
  11378. let fragmentNode = this.fragmentNode;
  11379. if ( fragmentNode.isOutputStructNode !== true ) {
  11380. fragmentNode = vec4( fragmentNode );
  11381. }
  11382. resultNode = this.setupOutput( builder, fragmentNode );
  11383. }
  11384. builder.stack.outputNode = resultNode;
  11385. builder.addFlow( 'fragment', builder.removeStack() );
  11386. // < OBSERVER >
  11387. builder.observer = this.setupObserver( builder );
  11388. }
  11389. /**
  11390. * Setups the clipping node.
  11391. *
  11392. * @param {NodeBuilder} builder - The current node builder.
  11393. * @return {ClippingNode} The clipping node.
  11394. */
  11395. setupClipping( builder ) {
  11396. if ( builder.clippingContext === null ) return null;
  11397. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11398. let result = null;
  11399. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11400. const samples = builder.renderer.samples;
  11401. if ( this.alphaToCoverage && samples > 1 ) {
  11402. // to be added to flow when the color/alpha value has been determined
  11403. result = clippingAlpha();
  11404. } else {
  11405. builder.stack.add( clipping() );
  11406. }
  11407. }
  11408. return result;
  11409. }
  11410. /**
  11411. * Setups the hardware clipping if available on the current device.
  11412. *
  11413. * @param {NodeBuilder} builder - The current node builder.
  11414. */
  11415. setupHardwareClipping( builder ) {
  11416. this.hardwareClipping = false;
  11417. if ( builder.clippingContext === null ) return;
  11418. const candidateCount = builder.clippingContext.unionPlanes.length;
  11419. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11420. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11421. builder.stack.add( hardwareClipping() );
  11422. this.hardwareClipping = true;
  11423. }
  11424. return;
  11425. }
  11426. /**
  11427. * Setups the depth of this material.
  11428. *
  11429. * @param {NodeBuilder} builder - The current node builder.
  11430. */
  11431. setupDepth( builder ) {
  11432. const { renderer, camera } = builder;
  11433. // Depth
  11434. let depthNode = this.depthNode;
  11435. if ( depthNode === null ) {
  11436. const mrt = renderer.getMRT();
  11437. if ( mrt && mrt.has( 'depth' ) ) {
  11438. depthNode = mrt.get( 'depth' );
  11439. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11440. if ( camera.isPerspectiveCamera ) {
  11441. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11442. } else {
  11443. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11444. }
  11445. }
  11446. }
  11447. if ( depthNode !== null ) {
  11448. depth.assign( depthNode ).append();
  11449. }
  11450. }
  11451. /**
  11452. * Setups the position node in view space. This method exists
  11453. * so derived node materials can modify the implementation e.g. sprite materials.
  11454. *
  11455. * @param {NodeBuilder} builder - The current node builder.
  11456. * @return {Node<vec3>} The position in view space.
  11457. */
  11458. setupPositionView( /*builder*/ ) {
  11459. return modelViewMatrix.mul( positionLocal ).xyz;
  11460. }
  11461. /**
  11462. * Setups the position in clip space.
  11463. *
  11464. * @param {NodeBuilder} builder - The current node builder.
  11465. * @return {Node<vec4>} The position in view space.
  11466. */
  11467. setupModelViewProjection( /*builder*/ ) {
  11468. return cameraProjectionMatrix.mul( positionView );
  11469. }
  11470. /**
  11471. * Setups the logic for the vertex stage.
  11472. *
  11473. * @param {NodeBuilder} builder - The current node builder.
  11474. * @return {Node<vec4>} The position in clip space.
  11475. */
  11476. setupVertex( builder ) {
  11477. builder.addStack();
  11478. this.setupPosition( builder );
  11479. builder.context.vertex = builder.removeStack();
  11480. return modelViewProjection;
  11481. }
  11482. /**
  11483. * Setups the computation of the position in local space.
  11484. *
  11485. * @param {NodeBuilder} builder - The current node builder.
  11486. * @return {Node<vec3>} The position in local space.
  11487. */
  11488. setupPosition( builder ) {
  11489. const { object, geometry } = builder;
  11490. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11491. morphReference( object ).append();
  11492. }
  11493. if ( object.isSkinnedMesh === true ) {
  11494. skinningReference( object ).append();
  11495. }
  11496. if ( this.displacementMap ) {
  11497. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11498. const displacementScale = materialReference( 'displacementScale', 'float' );
  11499. const displacementBias = materialReference( 'displacementBias', 'float' );
  11500. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11501. }
  11502. if ( object.isBatchedMesh ) {
  11503. batch( object ).append();
  11504. }
  11505. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11506. instancedMesh( object ).append();
  11507. }
  11508. if ( this.positionNode !== null ) {
  11509. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11510. }
  11511. return positionLocal;
  11512. }
  11513. /**
  11514. * Setups the computation of the material's diffuse color.
  11515. *
  11516. * @param {NodeBuilder} builder - The current node builder.
  11517. * @param {BufferGeometry} geometry - The geometry.
  11518. */
  11519. setupDiffuseColor( { object, geometry } ) {
  11520. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11521. // VERTEX COLORS
  11522. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11523. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11524. }
  11525. // Instanced colors
  11526. if ( object.instanceColor ) {
  11527. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11528. colorNode = instanceColor.mul( colorNode );
  11529. }
  11530. if ( object.isBatchedMesh && object._colorsTexture ) {
  11531. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11532. colorNode = batchColor.mul( colorNode );
  11533. }
  11534. // COLOR
  11535. diffuseColor.assign( colorNode );
  11536. // OPACITY
  11537. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11538. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11539. // ALPHA TEST
  11540. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11541. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11542. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11543. }
  11544. // ALPHA HASH
  11545. if ( this.alphaHash === true ) {
  11546. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11547. }
  11548. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11549. diffuseColor.a.assign( 1.0 );
  11550. }
  11551. }
  11552. /**
  11553. * Abstract interface method that can be implemented by derived materials
  11554. * to setup material-specific node variables.
  11555. *
  11556. * @abstract
  11557. * @param {NodeBuilder} builder - The current node builder.
  11558. */
  11559. setupVariants( /*builder*/ ) {
  11560. // Interface function.
  11561. }
  11562. /**
  11563. * Setups the outgoing light node variable
  11564. *
  11565. * @return {Node<vec3>} The outgoing light node.
  11566. */
  11567. setupOutgoingLight() {
  11568. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11569. }
  11570. /**
  11571. * Setups the normal node from the material.
  11572. *
  11573. * @return {Node<vec3>} The normal node.
  11574. */
  11575. setupNormal() {
  11576. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11577. }
  11578. /**
  11579. * Setups the environment node from the material.
  11580. *
  11581. * @param {NodeBuilder} builder - The current node builder.
  11582. * @return {Node<vec4>} The environment node.
  11583. */
  11584. setupEnvironment( /*builder*/ ) {
  11585. let node = null;
  11586. if ( this.envNode ) {
  11587. node = this.envNode;
  11588. } else if ( this.envMap ) {
  11589. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11590. }
  11591. return node;
  11592. }
  11593. /**
  11594. * Setups the light map node from the material.
  11595. *
  11596. * @param {NodeBuilder} builder - The current node builder.
  11597. * @return {Node<vec3>} The light map node.
  11598. */
  11599. setupLightMap( builder ) {
  11600. let node = null;
  11601. if ( builder.material.lightMap ) {
  11602. node = new IrradianceNode( materialLightMap );
  11603. }
  11604. return node;
  11605. }
  11606. /**
  11607. * Setups the lights node based on the scene, environment and material.
  11608. *
  11609. * @param {NodeBuilder} builder - The current node builder.
  11610. * @return {LightsNode} The lights node.
  11611. */
  11612. setupLights( builder ) {
  11613. const materialLightsNode = [];
  11614. //
  11615. const envNode = this.setupEnvironment( builder );
  11616. if ( envNode && envNode.isLightingNode ) {
  11617. materialLightsNode.push( envNode );
  11618. }
  11619. const lightMapNode = this.setupLightMap( builder );
  11620. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11621. materialLightsNode.push( lightMapNode );
  11622. }
  11623. if ( this.aoNode !== null || builder.material.aoMap ) {
  11624. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11625. materialLightsNode.push( new AONode( aoNode ) );
  11626. }
  11627. let lightsN = this.lightsNode || builder.lightsNode;
  11628. if ( materialLightsNode.length > 0 ) {
  11629. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11630. }
  11631. return lightsN;
  11632. }
  11633. /**
  11634. * This method should be implemented by most derived materials
  11635. * since it defines the material's lighting model.
  11636. *
  11637. * @abstract
  11638. * @param {NodeBuilder} builder - The current node builder.
  11639. * @return {LightingModel} The lighting model.
  11640. */
  11641. setupLightingModel( /*builder*/ ) {
  11642. // Interface function.
  11643. }
  11644. /**
  11645. * Setups the outgoing light node.
  11646. *
  11647. * @param {NodeBuilder} builder - The current node builder.
  11648. * @return {Node<vec3>} The outgoing light node.
  11649. */
  11650. setupLighting( builder ) {
  11651. const { material } = builder;
  11652. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11653. // OUTGOING LIGHT
  11654. const lights = this.lights === true || this.lightsNode !== null;
  11655. const lightsNode = lights ? this.setupLights( builder ) : null;
  11656. let outgoingLightNode = this.setupOutgoingLight( builder );
  11657. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11658. const lightingModel = this.setupLightingModel( builder );
  11659. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11660. } else if ( backdropNode !== null ) {
  11661. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11662. }
  11663. // EMISSIVE
  11664. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11665. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11666. outgoingLightNode = outgoingLightNode.add( emissive );
  11667. }
  11668. return outgoingLightNode;
  11669. }
  11670. /**
  11671. * Setups the output node.
  11672. *
  11673. * @param {NodeBuilder} builder - The current node builder.
  11674. * @param {Node<vec4>} outputNode - The existing output node.
  11675. * @return {Node<vec4>} The output node.
  11676. */
  11677. setupOutput( builder, outputNode ) {
  11678. // FOG
  11679. if ( this.fog === true ) {
  11680. const fogNode = builder.fogNode;
  11681. if ( fogNode ) {
  11682. output.assign( outputNode );
  11683. outputNode = vec4( fogNode );
  11684. }
  11685. }
  11686. return outputNode;
  11687. }
  11688. /**
  11689. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11690. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11691. * defining all material properties of the classic type in the node type.
  11692. *
  11693. * @param {Material} material - The material to copy properties with their values to this node material.
  11694. */
  11695. setDefaultValues( material ) {
  11696. // This approach is to reuse the native refreshUniforms*
  11697. // and turn available the use of features like transmission and environment in core
  11698. for ( const property in material ) {
  11699. const value = material[ property ];
  11700. if ( this[ property ] === undefined ) {
  11701. this[ property ] = value;
  11702. if ( value && value.clone ) this[ property ] = value.clone();
  11703. }
  11704. }
  11705. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11706. for ( const key in descriptors ) {
  11707. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11708. descriptors[ key ].get !== undefined ) {
  11709. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11710. }
  11711. }
  11712. }
  11713. /**
  11714. * Serializes this material to JSON.
  11715. *
  11716. * @param {(Object|String)?} meta - The meta information for serialization.
  11717. * @return {Object} The serialized node.
  11718. */
  11719. toJSON( meta ) {
  11720. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11721. if ( isRoot ) {
  11722. meta = {
  11723. textures: {},
  11724. images: {},
  11725. nodes: {}
  11726. };
  11727. }
  11728. const data = Material.prototype.toJSON.call( this, meta );
  11729. const nodeChildren = getNodeChildren( this );
  11730. data.inputNodes = {};
  11731. for ( const { property, childNode } of nodeChildren ) {
  11732. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11733. }
  11734. // TODO: Copied from Object3D.toJSON
  11735. function extractFromCache( cache ) {
  11736. const values = [];
  11737. for ( const key in cache ) {
  11738. const data = cache[ key ];
  11739. delete data.metadata;
  11740. values.push( data );
  11741. }
  11742. return values;
  11743. }
  11744. if ( isRoot ) {
  11745. const textures = extractFromCache( meta.textures );
  11746. const images = extractFromCache( meta.images );
  11747. const nodes = extractFromCache( meta.nodes );
  11748. if ( textures.length > 0 ) data.textures = textures;
  11749. if ( images.length > 0 ) data.images = images;
  11750. if ( nodes.length > 0 ) data.nodes = nodes;
  11751. }
  11752. return data;
  11753. }
  11754. /**
  11755. * Copies the properties of the given node material to this instance.
  11756. *
  11757. * @param {NodeMaterial} source - The material to copy.
  11758. * @return {NodeMaterial} A reference to this node material.
  11759. */
  11760. copy( source ) {
  11761. this.lightsNode = source.lightsNode;
  11762. this.envNode = source.envNode;
  11763. this.colorNode = source.colorNode;
  11764. this.normalNode = source.normalNode;
  11765. this.opacityNode = source.opacityNode;
  11766. this.backdropNode = source.backdropNode;
  11767. this.backdropAlphaNode = source.backdropAlphaNode;
  11768. this.alphaTestNode = source.alphaTestNode;
  11769. this.positionNode = source.positionNode;
  11770. this.geometryNode = source.geometryNode;
  11771. this.depthNode = source.depthNode;
  11772. this.shadowPositionNode = source.shadowPositionNode;
  11773. this.receivedShadowNode = source.receivedShadowNode;
  11774. this.castShadowNode = source.castShadowNode;
  11775. this.outputNode = source.outputNode;
  11776. this.mrtNode = source.mrtNode;
  11777. this.fragmentNode = source.fragmentNode;
  11778. this.vertexNode = source.vertexNode;
  11779. return super.copy( source );
  11780. }
  11781. }
  11782. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11783. /**
  11784. * Node material version of `LineBasicMaterial`.
  11785. *
  11786. * @augments NodeMaterial
  11787. */
  11788. class LineBasicNodeMaterial extends NodeMaterial {
  11789. static get type() {
  11790. return 'LineBasicNodeMaterial';
  11791. }
  11792. /**
  11793. * Constructs a new line basic node material.
  11794. *
  11795. * @param {Object?} parameters - The configuration parameter.
  11796. */
  11797. constructor( parameters ) {
  11798. super();
  11799. /**
  11800. * This flag can be used for type testing.
  11801. *
  11802. * @type {Boolean}
  11803. * @readonly
  11804. * @default true
  11805. */
  11806. this.isLineBasicNodeMaterial = true;
  11807. this.setDefaultValues( _defaultValues$d );
  11808. this.setValues( parameters );
  11809. }
  11810. }
  11811. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11812. /**
  11813. * Node material version of `LineDashedMaterial`.
  11814. *
  11815. * @augments NodeMaterial
  11816. */
  11817. class LineDashedNodeMaterial extends NodeMaterial {
  11818. static get type() {
  11819. return 'LineDashedNodeMaterial';
  11820. }
  11821. /**
  11822. * Constructs a new line dashed node material.
  11823. *
  11824. * @param {Object?} parameters - The configuration parameter.
  11825. */
  11826. constructor( parameters ) {
  11827. super();
  11828. /**
  11829. * This flag can be used for type testing.
  11830. *
  11831. * @type {Boolean}
  11832. * @readonly
  11833. * @default true
  11834. */
  11835. this.isLineDashedNodeMaterial = true;
  11836. this.setDefaultValues( _defaultValues$c );
  11837. /**
  11838. * The dash offset.
  11839. *
  11840. * @type {Number}
  11841. * @default 0
  11842. */
  11843. this.dashOffset = 0;
  11844. /**
  11845. * The offset of dash materials is by default inferred from the `dashOffset`
  11846. * property. This node property allows to overwrite the default
  11847. * and define the offset with a node instead.
  11848. *
  11849. * If you don't want to overwrite the offset but modify the existing
  11850. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11851. *
  11852. * @type {Node<float>?}
  11853. * @default null
  11854. */
  11855. this.offsetNode = null;
  11856. /**
  11857. * The scale of dash materials is by default inferred from the `scale`
  11858. * property. This node property allows to overwrite the default
  11859. * and define the scale with a node instead.
  11860. *
  11861. * If you don't want to overwrite the scale but modify the existing
  11862. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11863. *
  11864. * @type {Node<float>?}
  11865. * @default null
  11866. */
  11867. this.dashScaleNode = null;
  11868. /**
  11869. * The dash size of dash materials is by default inferred from the `dashSize`
  11870. * property. This node property allows to overwrite the default
  11871. * and define the dash size with a node instead.
  11872. *
  11873. * If you don't want to overwrite the dash size but modify the existing
  11874. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11875. *
  11876. * @type {Node<float>?}
  11877. * @default null
  11878. */
  11879. this.dashSizeNode = null;
  11880. /**
  11881. * The gap size of dash materials is by default inferred from the `gapSize`
  11882. * property. This node property allows to overwrite the default
  11883. * and define the gap size with a node instead.
  11884. *
  11885. * If you don't want to overwrite the gap size but modify the existing
  11886. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11887. *
  11888. * @type {Node<float>?}
  11889. * @default null
  11890. */
  11891. this.gapSizeNode = null;
  11892. this.setValues( parameters );
  11893. }
  11894. /**
  11895. * Setups the dash specific node variables.
  11896. *
  11897. * @param {NodeBuilder} builder - The current node builder.
  11898. */
  11899. setupVariants( /* builder */ ) {
  11900. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11901. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11902. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11903. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11904. dashSize.assign( dashSizeNode );
  11905. gapSize.assign( gapSizeNode );
  11906. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11907. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11908. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11909. }
  11910. }
  11911. /** @module ViewportSharedTextureNode **/
  11912. let _sharedFramebuffer = null;
  11913. /**
  11914. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11915. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11916. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11917. *
  11918. * @augments module:ViewportTextureNode~ViewportTextureNode
  11919. */
  11920. class ViewportSharedTextureNode extends ViewportTextureNode {
  11921. static get type() {
  11922. return 'ViewportSharedTextureNode';
  11923. }
  11924. /**
  11925. * Constructs a new viewport shared texture node.
  11926. *
  11927. * @param {Node} [uvNode=screenUV] - The uv node.
  11928. * @param {Node?} [levelNode=null] - The level node.
  11929. */
  11930. constructor( uvNode = screenUV, levelNode = null ) {
  11931. if ( _sharedFramebuffer === null ) {
  11932. _sharedFramebuffer = new FramebufferTexture();
  11933. }
  11934. super( uvNode, levelNode, _sharedFramebuffer );
  11935. }
  11936. updateReference() {
  11937. return this;
  11938. }
  11939. }
  11940. /**
  11941. * TSL function for creating a shared viewport texture node.
  11942. *
  11943. * @function
  11944. * @param {Node} [uvNode=screenUV] - The uv node.
  11945. * @param {Node?} [levelNode=null] - The level node.
  11946. * @returns {ViewportSharedTextureNode}
  11947. */
  11948. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11949. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11950. /**
  11951. * This node material can be used to render lines with a size larger than one
  11952. * by representing them as instanced meshes.
  11953. *
  11954. * @augments NodeMaterial
  11955. */
  11956. class Line2NodeMaterial extends NodeMaterial {
  11957. static get type() {
  11958. return 'Line2NodeMaterial';
  11959. }
  11960. /**
  11961. * Constructs a new node material for wide line rendering.
  11962. *
  11963. * @param {Object?} parameters - The configuration parameter.
  11964. */
  11965. constructor( parameters = {} ) {
  11966. super();
  11967. /**
  11968. * This flag can be used for type testing.
  11969. *
  11970. * @type {Boolean}
  11971. * @readonly
  11972. * @default true
  11973. */
  11974. this.isLine2NodeMaterial = true;
  11975. this.setDefaultValues( _defaultValues$b );
  11976. /**
  11977. * Whether vertex colors should be used or not.
  11978. *
  11979. * @type {Boolean}
  11980. * @default false
  11981. */
  11982. this.useColor = parameters.vertexColors;
  11983. /**
  11984. * The dash offset.
  11985. *
  11986. * @type {Number}
  11987. * @default 0
  11988. */
  11989. this.dashOffset = 0;
  11990. /**
  11991. * The line width.
  11992. *
  11993. * @type {Number}
  11994. * @default 0
  11995. */
  11996. this.lineWidth = 1;
  11997. /**
  11998. * Defines the lines color.
  11999. *
  12000. * @type {Node<vec3>?}
  12001. * @default null
  12002. */
  12003. this.lineColorNode = null;
  12004. /**
  12005. * Defines the offset.
  12006. *
  12007. * @type {Node<float>?}
  12008. * @default null
  12009. */
  12010. this.offsetNode = null;
  12011. /**
  12012. * Defines the dash scale.
  12013. *
  12014. * @type {Node<float>?}
  12015. * @default null
  12016. */
  12017. this.dashScaleNode = null;
  12018. /**
  12019. * Defines the dash size.
  12020. *
  12021. * @type {Node<float>?}
  12022. * @default null
  12023. */
  12024. this.dashSizeNode = null;
  12025. /**
  12026. * Defines the gap size.
  12027. *
  12028. * @type {Node<float>?}
  12029. * @default null
  12030. */
  12031. this.gapSizeNode = null;
  12032. /**
  12033. * Blending is set to `NoBlending` since transparency
  12034. * is not supported, yet.
  12035. *
  12036. * @type {Number}
  12037. * @default 0
  12038. */
  12039. this.blending = NoBlending;
  12040. this._useDash = parameters.dashed;
  12041. this._useAlphaToCoverage = true;
  12042. this._useWorldUnits = false;
  12043. this.setValues( parameters );
  12044. }
  12045. /**
  12046. * Setups the vertex and fragment stage of this node material.
  12047. *
  12048. * @param {NodeBuilder} builder - The current node builder.
  12049. */
  12050. setup( builder ) {
  12051. const { renderer } = builder;
  12052. const useAlphaToCoverage = this._useAlphaToCoverage;
  12053. const useColor = this.useColor;
  12054. const useDash = this._useDash;
  12055. const useWorldUnits = this._useWorldUnits;
  12056. const trimSegment = Fn( ( { start, end } ) => {
  12057. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12058. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12059. const nearEstimate = b.mul( - 0.5 ).div( a );
  12060. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12061. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12062. } ).setLayout( {
  12063. name: 'trimSegment',
  12064. type: 'vec4',
  12065. inputs: [
  12066. { name: 'start', type: 'vec4' },
  12067. { name: 'end', type: 'vec4' }
  12068. ]
  12069. } );
  12070. this.vertexNode = Fn( () => {
  12071. const instanceStart = attribute( 'instanceStart' );
  12072. const instanceEnd = attribute( 'instanceEnd' );
  12073. // camera space
  12074. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12075. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12076. if ( useDash ) {
  12077. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12078. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12079. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12080. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12081. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12082. lineDistance = lineDistance.add( offsetNode );
  12083. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12084. }
  12085. if ( useWorldUnits ) {
  12086. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12087. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12088. }
  12089. const aspect = viewport.z.div( viewport.w );
  12090. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12091. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12092. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12093. // perhaps there is a more elegant solution -- WestLangley
  12094. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12095. If( perspective, () => {
  12096. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12097. end.assign( trimSegment( { start: start, end: end } ) );
  12098. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12099. start.assign( trimSegment( { start: end, end: start } ) );
  12100. } );
  12101. } );
  12102. // clip space
  12103. const clipStart = cameraProjectionMatrix.mul( start );
  12104. const clipEnd = cameraProjectionMatrix.mul( end );
  12105. // ndc space
  12106. const ndcStart = clipStart.xyz.div( clipStart.w );
  12107. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12108. // direction
  12109. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12110. // account for clip-space aspect ratio
  12111. dir.x.assign( dir.x.mul( aspect ) );
  12112. dir.assign( dir.normalize() );
  12113. const clip = vec4().toVar();
  12114. if ( useWorldUnits ) {
  12115. // get the offset direction as perpendicular to the view vector
  12116. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12117. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12118. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12119. const worldFwd = worldDir.cross( worldUp );
  12120. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12121. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12122. // height offset
  12123. const hw = materialLineWidth.mul( 0.5 );
  12124. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12125. // don't extend the line if we're rendering dashes because we
  12126. // won't be rendering the endcaps
  12127. if ( ! useDash ) {
  12128. // cap extension
  12129. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12130. // add width to the box
  12131. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12132. // endcaps
  12133. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12134. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12135. } );
  12136. }
  12137. // project the worldpos
  12138. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12139. // shift the depth of the projected points so the line
  12140. // segments overlap neatly
  12141. const clipPose = vec3().toVar();
  12142. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12143. clip.z.assign( clipPose.z.mul( clip.w ) );
  12144. } else {
  12145. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12146. // undo aspect ratio adjustment
  12147. dir.x.assign( dir.x.div( aspect ) );
  12148. offset.x.assign( offset.x.div( aspect ) );
  12149. // sign flip
  12150. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12151. // endcaps
  12152. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12153. offset.assign( offset.sub( dir ) );
  12154. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12155. offset.assign( offset.add( dir ) );
  12156. } );
  12157. // adjust for linewidth
  12158. offset.assign( offset.mul( materialLineWidth ) );
  12159. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12160. offset.assign( offset.div( viewport.w ) );
  12161. // select end
  12162. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12163. // back to clip space
  12164. offset.assign( offset.mul( clip.w ) );
  12165. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12166. }
  12167. return clip;
  12168. } )();
  12169. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12170. const p13 = p1.sub( p3 );
  12171. const p43 = p4.sub( p3 );
  12172. const p21 = p2.sub( p1 );
  12173. const d1343 = p13.dot( p43 );
  12174. const d4321 = p43.dot( p21 );
  12175. const d1321 = p13.dot( p21 );
  12176. const d4343 = p43.dot( p43 );
  12177. const d2121 = p21.dot( p21 );
  12178. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12179. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12180. const mua = numer.div( denom ).clamp();
  12181. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12182. return vec2( mua, mub );
  12183. } );
  12184. this.colorNode = Fn( () => {
  12185. const vUv = uv();
  12186. if ( useDash ) {
  12187. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12188. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12189. dashSize.assign( dashSizeNode );
  12190. gapSize.assign( gapSizeNode );
  12191. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12192. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12193. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12194. }
  12195. const alpha = float( 1 ).toVar( 'alpha' );
  12196. if ( useWorldUnits ) {
  12197. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12198. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12199. // Find the closest points on the view ray and the line segment
  12200. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12201. const lineDir = worldEnd.sub( worldStart );
  12202. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12203. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12204. const p2 = rayEnd.mul( params.y );
  12205. const delta = p1.sub( p2 );
  12206. const len = delta.length();
  12207. const norm = len.div( materialLineWidth );
  12208. if ( ! useDash ) {
  12209. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12210. const dnorm = norm.fwidth();
  12211. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12212. } else {
  12213. norm.greaterThan( 0.5 ).discard();
  12214. }
  12215. }
  12216. } else {
  12217. // round endcaps
  12218. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12219. const a = vUv.x;
  12220. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12221. const len2 = a.mul( a ).add( b.mul( b ) );
  12222. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12223. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12224. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12225. } );
  12226. } else {
  12227. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  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. len2.greaterThan( 1.0 ).discard();
  12232. } );
  12233. }
  12234. }
  12235. let lineColorNode;
  12236. if ( this.lineColorNode ) {
  12237. lineColorNode = this.lineColorNode;
  12238. } else {
  12239. if ( useColor ) {
  12240. const instanceColorStart = attribute( 'instanceColorStart' );
  12241. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12242. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12243. lineColorNode = instanceColor.mul( materialColor );
  12244. } else {
  12245. lineColorNode = materialColor;
  12246. }
  12247. }
  12248. return vec4( lineColorNode, alpha );
  12249. } )();
  12250. if ( this.transparent ) {
  12251. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12252. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12253. }
  12254. super.setup( builder );
  12255. }
  12256. /**
  12257. * Whether the lines should sized in world units or not.
  12258. * When set to `false` the unit is pixel.
  12259. *
  12260. * @type {Boolean}
  12261. * @default false
  12262. */
  12263. get worldUnits() {
  12264. return this._useWorldUnits;
  12265. }
  12266. set worldUnits( value ) {
  12267. if ( this._useWorldUnits !== value ) {
  12268. this._useWorldUnits = value;
  12269. this.needsUpdate = true;
  12270. }
  12271. }
  12272. /**
  12273. * Whether the lines should be dashed or not.
  12274. *
  12275. * @type {Boolean}
  12276. * @default false
  12277. */
  12278. get dashed() {
  12279. return this._useDash;
  12280. }
  12281. set dashed( value ) {
  12282. if ( this._useDash !== value ) {
  12283. this._useDash = value;
  12284. this.needsUpdate = true;
  12285. }
  12286. }
  12287. /**
  12288. * Whether alpha to coverage should be used or not.
  12289. *
  12290. * @type {Boolean}
  12291. * @default true
  12292. */
  12293. get alphaToCoverage() {
  12294. return this._useAlphaToCoverage;
  12295. }
  12296. set alphaToCoverage( value ) {
  12297. if ( this._useAlphaToCoverage !== value ) {
  12298. this._useAlphaToCoverage = value;
  12299. this.needsUpdate = true;
  12300. }
  12301. }
  12302. }
  12303. /** @module Packing **/
  12304. /**
  12305. * Packs a direction vector into a color value.
  12306. *
  12307. * @method
  12308. * @param {Node<vec3>} node - The direction to pack.
  12309. * @return {Node<vec3>} The color.
  12310. */
  12311. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12312. /**
  12313. * Unpacks a color value into a direction vector.
  12314. *
  12315. * @method
  12316. * @param {Node<vec3>} node - The color to unpack.
  12317. * @return {Node<vec3>} The direction.
  12318. */
  12319. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12320. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12321. /**
  12322. * Node material version of `MeshNormalMaterial`.
  12323. *
  12324. * @augments NodeMaterial
  12325. */
  12326. class MeshNormalNodeMaterial extends NodeMaterial {
  12327. static get type() {
  12328. return 'MeshNormalNodeMaterial';
  12329. }
  12330. /**
  12331. * Constructs a new mesh normal node material.
  12332. *
  12333. * @param {Object?} parameters - The configuration parameter.
  12334. */
  12335. constructor( parameters ) {
  12336. super();
  12337. /**
  12338. * This flag can be used for type testing.
  12339. *
  12340. * @type {Boolean}
  12341. * @readonly
  12342. * @default true
  12343. */
  12344. this.isMeshNormalNodeMaterial = true;
  12345. this.setDefaultValues( _defaultValues$a );
  12346. this.setValues( parameters );
  12347. }
  12348. /**
  12349. * Overwrites the default implementation by computing the diffuse color
  12350. * based on the normal data.
  12351. */
  12352. setupDiffuseColor() {
  12353. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12354. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12355. }
  12356. }
  12357. /** @module EquirectUVNode **/
  12358. /**
  12359. * Can be used to compute texture coordinates for projecting an
  12360. * equirectangular texture onto a mesh for using it as the scene's
  12361. * background.
  12362. *
  12363. * ```js
  12364. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12365. * ```
  12366. *
  12367. * @augments TempNode
  12368. */
  12369. class EquirectUVNode extends TempNode {
  12370. static get type() {
  12371. return 'EquirectUVNode';
  12372. }
  12373. /**
  12374. * Constructs a new equirect uv node.
  12375. *
  12376. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12377. */
  12378. constructor( dirNode = positionWorldDirection ) {
  12379. super( 'vec2' );
  12380. /**
  12381. * A direction vector for sampling why is by default `positionWorldDirection`.
  12382. *
  12383. * @type {Node<vec3>}
  12384. */
  12385. this.dirNode = dirNode;
  12386. }
  12387. setup() {
  12388. const dir = this.dirNode;
  12389. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12390. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12391. return vec2( u, v );
  12392. }
  12393. }
  12394. /**
  12395. * TSL function for creating an equirect uv node.
  12396. *
  12397. * @function
  12398. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12399. * @returns {EquirectUVNode}
  12400. */
  12401. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12402. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12403. /**
  12404. * This class represents a cube render target. It is a special version
  12405. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12406. *
  12407. * @augments WebGLCubeRenderTarget
  12408. */
  12409. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12410. constructor( size = 1, options = {} ) {
  12411. super( size, options );
  12412. this.isCubeRenderTarget = true;
  12413. }
  12414. /**
  12415. * Converts the given equirectangular texture to a cube map.
  12416. *
  12417. * @param {Renderer} renderer - The renderer.
  12418. * @param {Texture} texture - The equirectangular texture.
  12419. * @return {CubeRenderTarget} A reference to this cube render target.
  12420. */
  12421. fromEquirectangularTexture( renderer, texture$1 ) {
  12422. const currentMinFilter = texture$1.minFilter;
  12423. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12424. texture$1.generateMipmaps = true;
  12425. this.texture.type = texture$1.type;
  12426. this.texture.colorSpace = texture$1.colorSpace;
  12427. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12428. this.texture.minFilter = texture$1.minFilter;
  12429. this.texture.magFilter = texture$1.magFilter;
  12430. const geometry = new BoxGeometry( 5, 5, 5 );
  12431. const uvNode = equirectUV( positionWorldDirection );
  12432. const material = new NodeMaterial();
  12433. material.colorNode = texture( texture$1, uvNode, 0 );
  12434. material.side = BackSide;
  12435. material.blending = NoBlending;
  12436. const mesh = new Mesh( geometry, material );
  12437. const scene = new Scene();
  12438. scene.add( mesh );
  12439. // Avoid blurred poles
  12440. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12441. const camera = new CubeCamera( 1, 10, this );
  12442. const currentMRT = renderer.getMRT();
  12443. renderer.setMRT( null );
  12444. camera.update( renderer, scene );
  12445. renderer.setMRT( currentMRT );
  12446. texture$1.minFilter = currentMinFilter;
  12447. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12448. mesh.geometry.dispose();
  12449. mesh.material.dispose();
  12450. return this;
  12451. }
  12452. }
  12453. /** @module CubeMapNode **/
  12454. const _cache$1 = new WeakMap();
  12455. /**
  12456. * This node can be used to automatically convert environment maps in the
  12457. * equirectangular format into the cube map format.
  12458. *
  12459. * @augments TempNode
  12460. */
  12461. class CubeMapNode extends TempNode {
  12462. static get type() {
  12463. return 'CubeMapNode';
  12464. }
  12465. /**
  12466. * Constructs a new cube map node.
  12467. *
  12468. * @param {Node} envNode - The node representing the environment map.
  12469. */
  12470. constructor( envNode ) {
  12471. super( 'vec3' );
  12472. /**
  12473. * The node representing the environment map.
  12474. *
  12475. * @type {Node}
  12476. */
  12477. this.envNode = envNode;
  12478. /**
  12479. * A reference to the internal cube texture.
  12480. *
  12481. * @private
  12482. * @type {CubeTexture}
  12483. * @default null
  12484. */
  12485. this._cubeTexture = null;
  12486. /**
  12487. * A reference to the internal cube texture node.
  12488. *
  12489. * @private
  12490. * @type {CubeTextureNode}
  12491. */
  12492. this._cubeTextureNode = cubeTexture();
  12493. const defaultTexture = new CubeTexture();
  12494. defaultTexture.isRenderTargetTexture = true;
  12495. /**
  12496. * A default cube texture that acts as a placeholder.
  12497. * It is used when the conversion from equirectangular to cube
  12498. * map has not finished yet for a given texture.
  12499. *
  12500. * @private
  12501. * @type {CubeTexture}
  12502. */
  12503. this._defaultTexture = defaultTexture;
  12504. /**
  12505. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12506. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12507. *
  12508. * @type {String}
  12509. * @default 'render'
  12510. */
  12511. this.updateBeforeType = NodeUpdateType.RENDER;
  12512. }
  12513. updateBefore( frame ) {
  12514. const { renderer, material } = frame;
  12515. const envNode = this.envNode;
  12516. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12517. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12518. if ( texture && texture.isTexture ) {
  12519. const mapping = texture.mapping;
  12520. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12521. // check for converted cubemap map
  12522. if ( _cache$1.has( texture ) ) {
  12523. const cubeMap = _cache$1.get( texture );
  12524. mapTextureMapping( cubeMap, texture.mapping );
  12525. this._cubeTexture = cubeMap;
  12526. } else {
  12527. // create cube map from equirectangular map
  12528. const image = texture.image;
  12529. if ( isEquirectangularMapReady$1( image ) ) {
  12530. const renderTarget = new CubeRenderTarget( image.height );
  12531. renderTarget.fromEquirectangularTexture( renderer, texture );
  12532. mapTextureMapping( renderTarget.texture, texture.mapping );
  12533. this._cubeTexture = renderTarget.texture;
  12534. _cache$1.set( texture, renderTarget.texture );
  12535. texture.addEventListener( 'dispose', onTextureDispose );
  12536. } else {
  12537. // default cube texture as fallback when equirectangular texture is not yet loaded
  12538. this._cubeTexture = this._defaultTexture;
  12539. }
  12540. }
  12541. //
  12542. this._cubeTextureNode.value = this._cubeTexture;
  12543. } else {
  12544. // envNode already refers to a cube map
  12545. this._cubeTextureNode = this.envNode;
  12546. }
  12547. }
  12548. }
  12549. }
  12550. setup( builder ) {
  12551. this.updateBefore( builder );
  12552. return this._cubeTextureNode;
  12553. }
  12554. }
  12555. /**
  12556. * Returns true if the given equirectangular image has been fully loaded
  12557. * and is ready for further processing.
  12558. *
  12559. * @private
  12560. * @param {Image} image - The equirectangular image to check.
  12561. * @return {Boolean} Whether the image is ready or not.
  12562. */
  12563. function isEquirectangularMapReady$1( image ) {
  12564. if ( image === null || image === undefined ) return false;
  12565. return image.height > 0;
  12566. }
  12567. /**
  12568. * This function is executed when `dispose()` is called on the equirectangular
  12569. * texture. In this case, the generated cube map with its render target
  12570. * is deleted as well.
  12571. *
  12572. * @private
  12573. * @param {Object} event - The event object.
  12574. */
  12575. function onTextureDispose( event ) {
  12576. const texture = event.target;
  12577. texture.removeEventListener( 'dispose', onTextureDispose );
  12578. const renderTarget = _cache$1.get( texture );
  12579. if ( renderTarget !== undefined ) {
  12580. _cache$1.delete( texture );
  12581. renderTarget.dispose();
  12582. }
  12583. }
  12584. /**
  12585. * This function makes sure the generated cube map uses the correct
  12586. * texture mapping that corresponds to the equirectangular original.
  12587. *
  12588. * @private
  12589. * @param {Texture} texture - The cube texture.
  12590. * @param {Number} mapping - The original texture mapping.
  12591. */
  12592. function mapTextureMapping( texture, mapping ) {
  12593. if ( mapping === EquirectangularReflectionMapping ) {
  12594. texture.mapping = CubeReflectionMapping;
  12595. } else if ( mapping === EquirectangularRefractionMapping ) {
  12596. texture.mapping = CubeRefractionMapping;
  12597. }
  12598. }
  12599. /**
  12600. * TSL function for creating a cube map node.
  12601. *
  12602. * @function
  12603. * @param {Node} envNode - The node representing the environment map.
  12604. * @returns {CubeMapNode}
  12605. */
  12606. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12607. /**
  12608. * Represents a basic model for Image-based lighting (IBL). The environment
  12609. * is defined via environment maps in the equirectangular or cube map format.
  12610. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12611. * or {@link MeshPhongNodeMaterial}.
  12612. *
  12613. * @augments LightingNode
  12614. */
  12615. class BasicEnvironmentNode extends LightingNode {
  12616. static get type() {
  12617. return 'BasicEnvironmentNode';
  12618. }
  12619. /**
  12620. * Constructs a new basic environment node.
  12621. *
  12622. * @param {Node} [envNode=null] - A node representing the environment.
  12623. */
  12624. constructor( envNode = null ) {
  12625. super();
  12626. /**
  12627. * A node representing the environment.
  12628. *
  12629. * @type {Node}
  12630. * @default null
  12631. */
  12632. this.envNode = envNode;
  12633. }
  12634. setup( builder ) {
  12635. // environment property is used in the finish() method of BasicLightingModel
  12636. builder.context.environment = cubeMapNode( this.envNode );
  12637. }
  12638. }
  12639. /**
  12640. * A specific version of {@link IrradianceNode} that is only relevant
  12641. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12642. * requires a special scaling factor for the light map.
  12643. *
  12644. * @augments LightingNode
  12645. */
  12646. class BasicLightMapNode extends LightingNode {
  12647. static get type() {
  12648. return 'BasicLightMapNode';
  12649. }
  12650. /**
  12651. * Constructs a new basic light map node.
  12652. *
  12653. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12654. */
  12655. constructor( lightMapNode = null ) {
  12656. super();
  12657. /**
  12658. * The light map node.
  12659. *
  12660. * @type {Node<vec3>?}
  12661. */
  12662. this.lightMapNode = lightMapNode;
  12663. }
  12664. setup( builder ) {
  12665. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12666. const RECIPROCAL_PI = float( 1 / Math.PI );
  12667. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12668. }
  12669. }
  12670. /**
  12671. * Abstract class for implementing lighting models. The module defines
  12672. * multiple methods that concrete lighting models can implement. These
  12673. * methods are executed at different points during the light evaluation
  12674. * process.
  12675. */
  12676. class LightingModel {
  12677. /**
  12678. * This method is intended for setting up lighting model and context data
  12679. * which are later used in the evaluation process.
  12680. *
  12681. * @abstract
  12682. * @param {ContextNode} input - The current node context.
  12683. * @param {StackNode} stack - The current stack.
  12684. * @param {NodeBuilder} builder - The current node builder.
  12685. */
  12686. start( /*input, stack, builder*/ ) { }
  12687. /**
  12688. * This method is intended for executing final tasks like final updates
  12689. * to the outgoing light.
  12690. *
  12691. * @abstract
  12692. * @param {ContextNode} input - The current node context.
  12693. * @param {StackNode} stack - The current stack.
  12694. * @param {NodeBuilder} builder - The current node builder.
  12695. */
  12696. finish( /*input, stack, builder*/ ) { }
  12697. /**
  12698. * This method is intended for implementing the direct light term and
  12699. * executed during the build process of directional, point and spot light nodes.
  12700. *
  12701. * @abstract
  12702. * @param {Object} input - The input data.
  12703. * @param {StackNode} stack - The current stack.
  12704. * @param {NodeBuilder} builder - The current node builder.
  12705. */
  12706. direct( /*input, stack, builder*/ ) { }
  12707. /**
  12708. * This method is intended for implementing the direct light term for
  12709. * rect area light nodes.
  12710. *
  12711. * @abstract
  12712. * @param {Object} input - The input data.
  12713. * @param {StackNode} stack - The current stack.
  12714. * @param {NodeBuilder} builder - The current node builder.
  12715. */
  12716. directRectArea( /*input, stack, builder*/ ) {}
  12717. /**
  12718. * This method is intended for implementing the indirect light term.
  12719. *
  12720. * @abstract
  12721. * @param {ContextNode} input - The current node context.
  12722. * @param {StackNode} stack - The current stack.
  12723. * @param {NodeBuilder} builder - The current node builder.
  12724. */
  12725. indirect( /*input, stack, builder*/ ) { }
  12726. /**
  12727. * This method is intended for implementing the ambient occlusion term.
  12728. * Unlike other methods, this method must be called manually by the lighting
  12729. * model in its indirect term.
  12730. *
  12731. * @abstract
  12732. * @param {ContextNode} input - The current node context.
  12733. * @param {StackNode} stack - The current stack.
  12734. * @param {NodeBuilder} builder - The current node builder.
  12735. */
  12736. ambientOcclusion( /*input, stack, builder*/ ) { }
  12737. }
  12738. /**
  12739. * Represents the lighting model for unlit materials. The only light contribution
  12740. * is baked indirect lighting modulated with ambient occlusion and the material's
  12741. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12742. *
  12743. * @augments LightingModel
  12744. */
  12745. class BasicLightingModel extends LightingModel {
  12746. /**
  12747. * Constructs a new basic lighting model.
  12748. */
  12749. constructor() {
  12750. super();
  12751. }
  12752. /**
  12753. * Implements the baked indirect lighting with its modulation.
  12754. *
  12755. * @param {ContextNode} context - The current node context.
  12756. * @param {StackNode} stack - The current stack.
  12757. * @param {NodeBuilder} builder - The current node builder.
  12758. */
  12759. indirect( context, stack, builder ) {
  12760. const ambientOcclusion = context.ambientOcclusion;
  12761. const reflectedLight = context.reflectedLight;
  12762. const irradianceLightMap = builder.context.irradianceLightMap;
  12763. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12764. // accumulation (baked indirect lighting only)
  12765. if ( irradianceLightMap ) {
  12766. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12767. } else {
  12768. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12769. }
  12770. // modulation
  12771. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12772. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12773. }
  12774. /**
  12775. * Implements the environment mapping.
  12776. *
  12777. * @param {ContextNode} context - The current node context.
  12778. * @param {StackNode} stack - The current stack.
  12779. * @param {NodeBuilder} builder - The current node builder.
  12780. */
  12781. finish( context, stack, builder ) {
  12782. const material = builder.material;
  12783. const outgoingLight = context.outgoingLight;
  12784. const envNode = builder.context.environment;
  12785. if ( envNode ) {
  12786. switch ( material.combine ) {
  12787. case MultiplyOperation:
  12788. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12789. break;
  12790. case MixOperation:
  12791. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12792. break;
  12793. case AddOperation:
  12794. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12795. break;
  12796. default:
  12797. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12798. break;
  12799. }
  12800. }
  12801. }
  12802. }
  12803. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12804. /**
  12805. * Node material version of `MeshBasicMaterial`.
  12806. *
  12807. * @augments NodeMaterial
  12808. */
  12809. class MeshBasicNodeMaterial extends NodeMaterial {
  12810. static get type() {
  12811. return 'MeshBasicNodeMaterial';
  12812. }
  12813. /**
  12814. * Constructs a new mesh basic node material.
  12815. *
  12816. * @param {Object?} parameters - The configuration parameter.
  12817. */
  12818. constructor( parameters ) {
  12819. super();
  12820. /**
  12821. * This flag can be used for type testing.
  12822. *
  12823. * @type {Boolean}
  12824. * @readonly
  12825. * @default true
  12826. */
  12827. this.isMeshBasicNodeMaterial = true;
  12828. /**
  12829. * Although the basic material is by definition unlit, we set
  12830. * this property to `true` since we use a lighting model to compute
  12831. * the outgoing light of the fragment shader.
  12832. *
  12833. * @type {Boolean}
  12834. * @default true
  12835. */
  12836. this.lights = true;
  12837. this.setDefaultValues( _defaultValues$9 );
  12838. this.setValues( parameters );
  12839. }
  12840. /**
  12841. * Basic materials are not affected by normal and bump maps so we
  12842. * return by default {@link module:Normal.normalView}.
  12843. *
  12844. * @return {Node<vec3>} The normal node.
  12845. */
  12846. setupNormal() {
  12847. return normalView; // see #28839
  12848. }
  12849. /**
  12850. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12851. * to implement the default environment mapping.
  12852. *
  12853. * @param {NodeBuilder} builder - The current node builder.
  12854. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12855. */
  12856. setupEnvironment( builder ) {
  12857. const envNode = super.setupEnvironment( builder );
  12858. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12859. }
  12860. /**
  12861. * This method must be overwritten since light maps are evaluated
  12862. * with a special scaling factor for basic materials.
  12863. *
  12864. * @param {NodeBuilder} builder - The current node builder.
  12865. * @return {BasicLightMapNode<vec3>?} The light map node.
  12866. */
  12867. setupLightMap( builder ) {
  12868. let node = null;
  12869. if ( builder.material.lightMap ) {
  12870. node = new BasicLightMapNode( materialLightMap );
  12871. }
  12872. return node;
  12873. }
  12874. /**
  12875. * The material overwrites this method because `lights` is set to `true` but
  12876. * we still want to return the diffuse color as the outgoing light.
  12877. *
  12878. * @return {Node<vec3>} The outgoing light node.
  12879. */
  12880. setupOutgoingLight() {
  12881. return diffuseColor.rgb;
  12882. }
  12883. /**
  12884. * Setups the lighting model.
  12885. *
  12886. * @return {BasicLightingModel} The lighting model.
  12887. */
  12888. setupLightingModel() {
  12889. return new BasicLightingModel();
  12890. }
  12891. }
  12892. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12893. // Original approximation by Christophe Schlick '94
  12894. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12895. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12896. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12897. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12898. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12899. } ); // validated
  12900. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12901. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12902. } ); // validated
  12903. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12904. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12905. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12906. } );
  12907. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12908. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12909. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12910. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12911. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12912. const G = G_BlinnPhong_Implicit();
  12913. const D = D_BlinnPhong( { dotNH } );
  12914. return F.mul( G ).mul( D );
  12915. } );
  12916. /**
  12917. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12918. *
  12919. * @augments BasicLightingModel
  12920. */
  12921. class PhongLightingModel extends BasicLightingModel {
  12922. /**
  12923. * Constructs a new phong lighting model.
  12924. *
  12925. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12926. */
  12927. constructor( specular = true ) {
  12928. super();
  12929. /**
  12930. * Whether specular is supported or not. Set this to `false` if you are
  12931. * looking for a Lambert-like material meaning a material for non-shiny
  12932. * surfaces, without specular highlights.
  12933. *
  12934. * @type {Boolean}
  12935. * @default true
  12936. */
  12937. this.specular = specular;
  12938. }
  12939. /**
  12940. * Implements the direct lighting. The specular portion is optional an can be controlled
  12941. * with the {@link PhongLightingModel#specular} flag.
  12942. *
  12943. * @param {Object} input - The input data.
  12944. * @param {StackNode} stack - The current stack.
  12945. * @param {NodeBuilder} builder - The current node builder.
  12946. */
  12947. direct( { lightDirection, lightColor, reflectedLight } ) {
  12948. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12949. const irradiance = dotNL.mul( lightColor );
  12950. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12951. if ( this.specular === true ) {
  12952. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12953. }
  12954. }
  12955. /**
  12956. * Implements the indirect lighting.
  12957. *
  12958. * @param {ContextNode} input - The current node context.
  12959. * @param {StackNode} stack - The current stack.
  12960. * @param {NodeBuilder} builder - The current node builder.
  12961. */
  12962. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12963. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12965. }
  12966. }
  12967. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12968. /**
  12969. * Node material version of `MeshLambertMaterial`.
  12970. *
  12971. * @augments NodeMaterial
  12972. */
  12973. class MeshLambertNodeMaterial extends NodeMaterial {
  12974. static get type() {
  12975. return 'MeshLambertNodeMaterial';
  12976. }
  12977. /**
  12978. * Constructs a new mesh lambert node material.
  12979. *
  12980. * @param {Object?} parameters - The configuration parameter.
  12981. */
  12982. constructor( parameters ) {
  12983. super();
  12984. /**
  12985. * This flag can be used for type testing.
  12986. *
  12987. * @type {Boolean}
  12988. * @readonly
  12989. * @default true
  12990. */
  12991. this.isMeshLambertNodeMaterial = true;
  12992. /**
  12993. * Set to `true` because lambert materials react on lights.
  12994. *
  12995. * @type {Boolean}
  12996. * @default true
  12997. */
  12998. this.lights = true;
  12999. this.setDefaultValues( _defaultValues$8 );
  13000. this.setValues( parameters );
  13001. }
  13002. /**
  13003. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13004. * to implement the default environment mapping.
  13005. *
  13006. * @param {NodeBuilder} builder - The current node builder.
  13007. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13008. */
  13009. setupEnvironment( builder ) {
  13010. const envNode = super.setupEnvironment( builder );
  13011. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13012. }
  13013. /**
  13014. * Setups the lighting model.
  13015. *
  13016. * @return {PhongLightingModel} The lighting model.
  13017. */
  13018. setupLightingModel( /*builder*/ ) {
  13019. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13020. }
  13021. }
  13022. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13023. /**
  13024. * Node material version of `MeshPhongMaterial`.
  13025. *
  13026. * @augments NodeMaterial
  13027. */
  13028. class MeshPhongNodeMaterial extends NodeMaterial {
  13029. static get type() {
  13030. return 'MeshPhongNodeMaterial';
  13031. }
  13032. /**
  13033. * Constructs a new mesh lambert node material.
  13034. *
  13035. * @param {Object?} parameters - The configuration parameter.
  13036. */
  13037. constructor( parameters ) {
  13038. super();
  13039. /**
  13040. * This flag can be used for type testing.
  13041. *
  13042. * @type {Boolean}
  13043. * @readonly
  13044. * @default true
  13045. */
  13046. this.isMeshPhongNodeMaterial = true;
  13047. /**
  13048. * Set to `true` because phong materials react on lights.
  13049. *
  13050. * @type {Boolean}
  13051. * @default true
  13052. */
  13053. this.lights = true;
  13054. /**
  13055. * The shininess of phong materials is by default inferred from the `shininess`
  13056. * property. This node property allows to overwrite the default
  13057. * and define the shininess with a node instead.
  13058. *
  13059. * If you don't want to overwrite the shininess but modify the existing
  13060. * value instead, use {@link module:MaterialNode.materialShininess}.
  13061. *
  13062. * @type {Node<float>?}
  13063. * @default null
  13064. */
  13065. this.shininessNode = null;
  13066. /**
  13067. * The specular color of phong materials is by default inferred from the
  13068. * `specular` property. This node property allows to overwrite the default
  13069. * and define the specular color with a node instead.
  13070. *
  13071. * If you don't want to overwrite the specular color but modify the existing
  13072. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13073. *
  13074. * @type {Node<vec3>?}
  13075. * @default null
  13076. */
  13077. this.specularNode = null;
  13078. this.setDefaultValues( _defaultValues$7 );
  13079. this.setValues( parameters );
  13080. }
  13081. /**
  13082. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13083. * to implement the default environment mapping.
  13084. *
  13085. * @param {NodeBuilder} builder - The current node builder.
  13086. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13087. */
  13088. setupEnvironment( builder ) {
  13089. const envNode = super.setupEnvironment( builder );
  13090. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13091. }
  13092. /**
  13093. * Setups the lighting model.
  13094. *
  13095. * @return {PhongLightingModel} The lighting model.
  13096. */
  13097. setupLightingModel( /*builder*/ ) {
  13098. return new PhongLightingModel();
  13099. }
  13100. /**
  13101. * Setups the phong specific node variables.
  13102. *
  13103. * @param {NodeBuilder} builder - The current node builder.
  13104. */
  13105. setupVariants( /*builder*/ ) {
  13106. // SHININESS
  13107. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13108. shininess.assign( shininessNode );
  13109. // SPECULAR COLOR
  13110. const specularNode = this.specularNode || materialSpecular;
  13111. specularColor.assign( specularNode );
  13112. }
  13113. copy( source ) {
  13114. this.shininessNode = source.shininessNode;
  13115. this.specularNode = source.specularNode;
  13116. return super.copy( source );
  13117. }
  13118. }
  13119. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13120. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13121. return float( 0 );
  13122. }
  13123. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13124. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13125. return geometryRoughness;
  13126. } );
  13127. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13128. const { roughness } = inputs;
  13129. const geometryRoughness = getGeometryRoughness();
  13130. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13131. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13132. roughnessFactor = roughnessFactor.min( 1.0 );
  13133. return roughnessFactor;
  13134. } );
  13135. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13136. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13137. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13138. const a2 = alpha.pow2();
  13139. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13140. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13141. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13142. } ).setLayout( {
  13143. name: 'V_GGX_SmithCorrelated',
  13144. type: 'float',
  13145. inputs: [
  13146. { name: 'alpha', type: 'float' },
  13147. { name: 'dotNL', type: 'float' },
  13148. { name: 'dotNV', type: 'float' }
  13149. ]
  13150. } ); // validated
  13151. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13152. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13153. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13154. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13155. const v = div( 0.5, gv.add( gl ) );
  13156. return v.saturate();
  13157. } ).setLayout( {
  13158. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13159. type: 'float',
  13160. inputs: [
  13161. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13162. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13163. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13164. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13165. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13166. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13167. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13168. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13169. ]
  13170. } );
  13171. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13172. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13173. // alpha is "roughness squared" in Disney’s reparameterization
  13174. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13175. const a2 = alpha.pow2();
  13176. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13177. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13178. } ).setLayout( {
  13179. name: 'D_GGX',
  13180. type: 'float',
  13181. inputs: [
  13182. { name: 'alpha', type: 'float' },
  13183. { name: 'dotNH', type: 'float' }
  13184. ]
  13185. } ); // validated
  13186. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13187. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13188. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13189. const a2 = alphaT.mul( alphaB );
  13190. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13191. const v2 = v.dot( v );
  13192. const w2 = a2.div( v2 );
  13193. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13194. } ).setLayout( {
  13195. name: 'D_GGX_Anisotropic',
  13196. type: 'float',
  13197. inputs: [
  13198. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13199. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13200. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13201. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13202. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13203. ]
  13204. } );
  13205. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13206. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13207. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13208. const normalView = inputs.normalView || transformedNormalView;
  13209. const alpha = roughness.pow2(); // UE4's roughness
  13210. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13211. const dotNL = normalView.dot( lightDirection ).clamp();
  13212. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13213. const dotNH = normalView.dot( halfDir ).clamp();
  13214. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13215. let F = F_Schlick( { f0, f90, dotVH } );
  13216. let V, D;
  13217. if ( defined( USE_IRIDESCENCE ) ) {
  13218. F = iridescence.mix( F, f );
  13219. }
  13220. if ( defined( USE_ANISOTROPY ) ) {
  13221. const dotTL = anisotropyT.dot( lightDirection );
  13222. const dotTV = anisotropyT.dot( positionViewDirection );
  13223. const dotTH = anisotropyT.dot( halfDir );
  13224. const dotBL = anisotropyB.dot( lightDirection );
  13225. const dotBV = anisotropyB.dot( positionViewDirection );
  13226. const dotBH = anisotropyB.dot( halfDir );
  13227. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13228. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13229. } else {
  13230. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13231. D = D_GGX( { alpha, dotNH } );
  13232. }
  13233. return F.mul( V ).mul( D );
  13234. } ); // validated
  13235. // Analytical approximation of the DFG LUT, one half of the
  13236. // split-sum approximation used in indirect specular lighting.
  13237. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13238. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13239. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13240. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13241. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13242. const r = roughness.mul( c0 ).add( c1 );
  13243. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13244. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13245. return fab;
  13246. } ).setLayout( {
  13247. name: 'DFGApprox',
  13248. type: 'vec2',
  13249. inputs: [
  13250. { name: 'roughness', type: 'float' },
  13251. { name: 'dotNV', type: 'vec3' }
  13252. ]
  13253. } );
  13254. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13255. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13256. const fab = DFGApprox( { dotNV, roughness } );
  13257. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13258. } );
  13259. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13260. const x = dotVH.oneMinus().saturate();
  13261. const x2 = x.mul( x );
  13262. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13263. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13264. } ).setLayout( {
  13265. name: 'Schlick_to_F0',
  13266. type: 'vec3',
  13267. inputs: [
  13268. { name: 'f', type: 'vec3' },
  13269. { name: 'f90', type: 'float' },
  13270. { name: 'dotVH', type: 'float' }
  13271. ]
  13272. } );
  13273. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13274. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13275. const alpha = roughness.pow2();
  13276. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13277. const invAlpha = float( 1.0 ).div( alpha );
  13278. const cos2h = dotNH.pow2();
  13279. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13280. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13281. } ).setLayout( {
  13282. name: 'D_Charlie',
  13283. type: 'float',
  13284. inputs: [
  13285. { name: 'roughness', type: 'float' },
  13286. { name: 'dotNH', type: 'float' }
  13287. ]
  13288. } );
  13289. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13290. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13291. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13292. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13293. } ).setLayout( {
  13294. name: 'V_Neubelt',
  13295. type: 'float',
  13296. inputs: [
  13297. { name: 'dotNV', type: 'float' },
  13298. { name: 'dotNL', type: 'float' }
  13299. ]
  13300. } );
  13301. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13302. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13303. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13304. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13305. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13306. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13307. const V = V_Neubelt( { dotNV, dotNL } );
  13308. return sheen.mul( D ).mul( V );
  13309. } );
  13310. // Rect Area Light
  13311. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13312. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13313. // code: https://github.com/selfshadow/ltc_code/
  13314. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13315. const LUT_SIZE = 64.0;
  13316. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13317. const LUT_BIAS = 0.5 / LUT_SIZE;
  13318. const dotNV = N.dot( V ).saturate();
  13319. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13320. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13321. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13322. return uv;
  13323. } ).setLayout( {
  13324. name: 'LTC_Uv',
  13325. type: 'vec2',
  13326. inputs: [
  13327. { name: 'N', type: 'vec3' },
  13328. { name: 'V', type: 'vec3' },
  13329. { name: 'roughness', type: 'float' }
  13330. ]
  13331. } );
  13332. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13333. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13334. // An approximation of the form factor of a horizon-clipped rectangle.
  13335. const l = f.length();
  13336. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13337. } ).setLayout( {
  13338. name: 'LTC_ClippedSphereFormFactor',
  13339. type: 'float',
  13340. inputs: [
  13341. { name: 'f', type: 'vec3' }
  13342. ]
  13343. } );
  13344. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13345. const x = v1.dot( v2 );
  13346. const y = x.abs().toVar();
  13347. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13348. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13349. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13350. const v = a.div( b );
  13351. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13352. return v1.cross( v2 ).mul( theta_sintheta );
  13353. } ).setLayout( {
  13354. name: 'LTC_EdgeVectorFormFactor',
  13355. type: 'vec3',
  13356. inputs: [
  13357. { name: 'v1', type: 'vec3' },
  13358. { name: 'v2', type: 'vec3' }
  13359. ]
  13360. } );
  13361. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13362. // bail if point is on back side of plane of light
  13363. // assumes ccw winding order of light vertices
  13364. const v1 = p1.sub( p0 ).toVar();
  13365. const v2 = p3.sub( p0 ).toVar();
  13366. const lightNormal = v1.cross( v2 );
  13367. const result = vec3().toVar();
  13368. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13369. // construct orthonormal basis around N
  13370. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13371. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13372. // compute transform
  13373. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13374. // transform rect
  13375. // & project rect onto sphere
  13376. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13377. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13378. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13379. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13380. // calculate vector form factor
  13381. const vectorFormFactor = vec3( 0 ).toVar();
  13382. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13383. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13384. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13385. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13386. // adjust for horizon clipping
  13387. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13388. } );
  13389. return result;
  13390. } ).setLayout( {
  13391. name: 'LTC_Evaluate',
  13392. type: 'vec3',
  13393. inputs: [
  13394. { name: 'N', type: 'vec3' },
  13395. { name: 'V', type: 'vec3' },
  13396. { name: 'P', type: 'vec3' },
  13397. { name: 'mInv', type: 'mat3' },
  13398. { name: 'p0', type: 'vec3' },
  13399. { name: 'p1', type: 'vec3' },
  13400. { name: 'p2', type: 'vec3' },
  13401. { name: 'p3', type: 'vec3' }
  13402. ]
  13403. } );
  13404. /** @module TextureBicubic **/
  13405. // Mipped Bicubic Texture Filtering by N8
  13406. // https://www.shadertoy.com/view/Dl2SDW
  13407. const bC = 1.0 / 6.0;
  13408. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13409. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13410. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13411. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13412. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13413. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13414. // h0 and h1 are the two offset functions
  13415. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13416. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13417. const bicubic = ( textureNode, texelSize, lod ) => {
  13418. const uv = textureNode.uvNode;
  13419. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13420. const iuv = floor( uvScaled );
  13421. const fuv = fract( uvScaled );
  13422. const g0x = g0( fuv.x );
  13423. const g1x = g1( fuv.x );
  13424. const h0x = h0( fuv.x );
  13425. const h1x = h1( fuv.x );
  13426. const h0y = h0( fuv.y );
  13427. const h1y = h1( fuv.y );
  13428. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13429. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13430. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13431. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13432. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13433. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13434. return a.add( b );
  13435. };
  13436. /**
  13437. * Applies mipped bicubic texture filtering to the given texture node.
  13438. *
  13439. * @method
  13440. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13441. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13442. * @return {Node} The filtered texture sample.
  13443. */
  13444. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13445. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13446. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13447. const fLodSizeInv = div( 1.0, fLodSize );
  13448. const cLodSizeInv = div( 1.0, cLodSize );
  13449. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13450. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13451. return fract( lodNode ).mix( fSample, cSample );
  13452. } );
  13453. //
  13454. // Transmission
  13455. //
  13456. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13457. // Direction of refracted light.
  13458. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13459. // Compute rotation-independent scaling of the model matrix.
  13460. const modelScale = vec3(
  13461. length( modelMatrix[ 0 ].xyz ),
  13462. length( modelMatrix[ 1 ].xyz ),
  13463. length( modelMatrix[ 2 ].xyz )
  13464. );
  13465. // The thickness is specified in local space.
  13466. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13467. } ).setLayout( {
  13468. name: 'getVolumeTransmissionRay',
  13469. type: 'vec3',
  13470. inputs: [
  13471. { name: 'n', type: 'vec3' },
  13472. { name: 'v', type: 'vec3' },
  13473. { name: 'thickness', type: 'float' },
  13474. { name: 'ior', type: 'float' },
  13475. { name: 'modelMatrix', type: 'mat4' }
  13476. ]
  13477. } );
  13478. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13479. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13480. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13481. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13482. } ).setLayout( {
  13483. name: 'applyIorToRoughness',
  13484. type: 'float',
  13485. inputs: [
  13486. { name: 'roughness', type: 'float' },
  13487. { name: 'ior', type: 'float' }
  13488. ]
  13489. } );
  13490. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13491. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13492. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13493. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13494. const transmissionSample = vTexture.sample( fragCoord );
  13495. //const transmissionSample = viewportMipTexture( fragCoord );
  13496. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13497. return textureBicubic( transmissionSample, lod );
  13498. } );
  13499. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13500. If( attenuationDistance.notEqual( 0 ), () => {
  13501. // Compute light attenuation using Beer's law.
  13502. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13503. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13504. return transmittance;
  13505. } );
  13506. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13507. return vec3( 1.0 );
  13508. } ).setLayout( {
  13509. name: 'volumeAttenuation',
  13510. type: 'vec3',
  13511. inputs: [
  13512. { name: 'transmissionDistance', type: 'float' },
  13513. { name: 'attenuationColor', type: 'vec3' },
  13514. { name: 'attenuationDistance', type: 'float' }
  13515. ]
  13516. } );
  13517. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13518. let transmittedLight, transmittance;
  13519. if ( dispersion ) {
  13520. transmittedLight = vec4().toVar();
  13521. transmittance = vec3().toVar();
  13522. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13523. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13524. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13525. const ior = iors.element( i );
  13526. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13527. const refractedRayExit = position.add( transmissionRay );
  13528. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13529. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13530. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13531. refractionCoords.addAssign( 1.0 );
  13532. refractionCoords.divAssign( 2.0 );
  13533. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13534. // Sample framebuffer to get pixel the refracted ray hits.
  13535. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13536. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13537. transmittedLight.a.addAssign( transmissionSample.a );
  13538. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13539. } );
  13540. transmittedLight.a.divAssign( 3.0 );
  13541. } else {
  13542. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13543. const refractedRayExit = position.add( transmissionRay );
  13544. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13545. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13546. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13547. refractionCoords.addAssign( 1.0 );
  13548. refractionCoords.divAssign( 2.0 );
  13549. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13550. // Sample framebuffer to get pixel the refracted ray hits.
  13551. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13552. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13553. }
  13554. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13555. const dotNV = n.dot( v ).clamp();
  13556. // Get the specular component.
  13557. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13558. dotNV,
  13559. specularColor,
  13560. specularF90,
  13561. roughness
  13562. } ) );
  13563. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13564. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13565. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13566. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13567. } );
  13568. //
  13569. // Iridescence
  13570. //
  13571. // XYZ to linear-sRGB color space
  13572. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13573. 3.2404542, - 0.9692660, 0.0556434,
  13574. - 1.5371385, 1.8760108, - 0.2040259,
  13575. - 0.4985314, 0.0415560, 1.0572252
  13576. );
  13577. // Assume air interface for top
  13578. // Note: We don't handle the case fresnel0 == 1
  13579. const Fresnel0ToIor = ( fresnel0 ) => {
  13580. const sqrtF0 = fresnel0.sqrt();
  13581. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13582. };
  13583. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13584. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13585. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13586. };
  13587. // Fresnel equations for dielectric/dielectric interfaces.
  13588. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13589. // Evaluation XYZ sensitivity curves in Fourier space
  13590. const evalSensitivity = ( OPD, shift ) => {
  13591. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13592. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13593. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13594. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13595. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  13596. 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() );
  13597. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13598. const rgb = XYZ_TO_REC709.mul( xyz );
  13599. return rgb;
  13600. };
  13601. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13602. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13603. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13604. // Evaluate the cosTheta on the base layer (Snell law)
  13605. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13606. // Handle TIR:
  13607. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13608. If( cosTheta2Sq.lessThan( 0 ), () => {
  13609. return vec3( 1.0 );
  13610. } );
  13611. const cosTheta2 = cosTheta2Sq.sqrt();
  13612. // First interface
  13613. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13614. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13615. //const R21 = R12;
  13616. const T121 = R12.oneMinus();
  13617. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13618. const phi21 = float( Math.PI ).sub( phi12 );
  13619. // Second interface
  13620. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13621. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13622. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13623. const phi23 = vec3(
  13624. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13625. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13626. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13627. );
  13628. // Phase shift
  13629. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13630. const phi = vec3( phi21 ).add( phi23 );
  13631. // Compound terms
  13632. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13633. const r123 = R123.sqrt();
  13634. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13635. // Reflectance term for m = 0 (DC term amplitude)
  13636. const C0 = R12.add( Rs );
  13637. const I = C0.toVar();
  13638. // Reflectance term for m > 0 (pairs of diracs)
  13639. const Cm = Rs.sub( T121 ).toVar();
  13640. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13641. Cm.mulAssign( r123 );
  13642. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13643. I.addAssign( Cm.mul( Sm ) );
  13644. } );
  13645. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13646. return I.max( vec3( 0.0 ) );
  13647. } ).setLayout( {
  13648. name: 'evalIridescence',
  13649. type: 'vec3',
  13650. inputs: [
  13651. { name: 'outsideIOR', type: 'float' },
  13652. { name: 'eta2', type: 'float' },
  13653. { name: 'cosTheta1', type: 'float' },
  13654. { name: 'thinFilmThickness', type: 'float' },
  13655. { name: 'baseF0', type: 'vec3' }
  13656. ]
  13657. } );
  13658. //
  13659. // Sheen
  13660. //
  13661. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13662. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13663. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13664. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13665. const dotNV = normal.dot( viewDir ).saturate();
  13666. const r2 = roughness.pow2();
  13667. const a = select(
  13668. roughness.lessThan( 0.25 ),
  13669. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13670. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13671. );
  13672. const b = select(
  13673. roughness.lessThan( 0.25 ),
  13674. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13675. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13676. );
  13677. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13678. return DG.mul( 1.0 / Math.PI ).saturate();
  13679. } );
  13680. const clearcoatF0 = vec3( 0.04 );
  13681. const clearcoatF90 = float( 1 );
  13682. /**
  13683. * Represents the lighting model for a PBR material.
  13684. *
  13685. * @augments LightingModel
  13686. */
  13687. class PhysicalLightingModel extends LightingModel {
  13688. /**
  13689. * Constructs a new physical lighting model.
  13690. *
  13691. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13692. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13693. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13694. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13695. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13696. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13697. */
  13698. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13699. super();
  13700. /**
  13701. * Whether clearcoat is supported or not.
  13702. *
  13703. * @type {Boolean}
  13704. * @default false
  13705. */
  13706. this.clearcoat = clearcoat;
  13707. /**
  13708. * Whether sheen is supported or not.
  13709. *
  13710. * @type {Boolean}
  13711. * @default false
  13712. */
  13713. this.sheen = sheen;
  13714. /**
  13715. * Whether iridescence is supported or not.
  13716. *
  13717. * @type {Boolean}
  13718. * @default false
  13719. */
  13720. this.iridescence = iridescence;
  13721. /**
  13722. * Whether anisotropy is supported or not.
  13723. *
  13724. * @type {Boolean}
  13725. * @default false
  13726. */
  13727. this.anisotropy = anisotropy;
  13728. /**
  13729. * Whether transmission is supported or not.
  13730. *
  13731. * @type {Boolean}
  13732. * @default false
  13733. */
  13734. this.transmission = transmission;
  13735. /**
  13736. * Whether dispersion is supported or not.
  13737. *
  13738. * @type {Boolean}
  13739. * @default false
  13740. */
  13741. this.dispersion = dispersion;
  13742. /**
  13743. * The clear coat radiance.
  13744. *
  13745. * @type {Node?}
  13746. * @default null
  13747. */
  13748. this.clearcoatRadiance = null;
  13749. /**
  13750. * The clear coat specular direct.
  13751. *
  13752. * @type {Node?}
  13753. * @default null
  13754. */
  13755. this.clearcoatSpecularDirect = null;
  13756. /**
  13757. * The clear coat specular indirect.
  13758. *
  13759. * @type {Node?}
  13760. * @default null
  13761. */
  13762. this.clearcoatSpecularIndirect = null;
  13763. /**
  13764. * The sheen specular direct.
  13765. *
  13766. * @type {Node?}
  13767. * @default null
  13768. */
  13769. this.sheenSpecularDirect = null;
  13770. /**
  13771. * The sheen specular indirect.
  13772. *
  13773. * @type {Node?}
  13774. * @default null
  13775. */
  13776. this.sheenSpecularIndirect = null;
  13777. /**
  13778. * The iridescence Fresnel.
  13779. *
  13780. * @type {Node?}
  13781. * @default null
  13782. */
  13783. this.iridescenceFresnel = null;
  13784. /**
  13785. * The iridescence F0.
  13786. *
  13787. * @type {Node?}
  13788. * @default null
  13789. */
  13790. this.iridescenceF0 = null;
  13791. }
  13792. /**
  13793. * Depending on what features are requested, the method prepares certain node variables
  13794. * which are later used for lighting computations.
  13795. *
  13796. * @param {ContextNode} context - The current node context.
  13797. */
  13798. start( context ) {
  13799. if ( this.clearcoat === true ) {
  13800. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13801. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13802. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13803. }
  13804. if ( this.sheen === true ) {
  13805. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13806. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13807. }
  13808. if ( this.iridescence === true ) {
  13809. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13810. this.iridescenceFresnel = evalIridescence( {
  13811. outsideIOR: float( 1.0 ),
  13812. eta2: iridescenceIOR,
  13813. cosTheta1: dotNVi,
  13814. thinFilmThickness: iridescenceThickness,
  13815. baseF0: specularColor
  13816. } );
  13817. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13818. }
  13819. if ( this.transmission === true ) {
  13820. const position = positionWorld;
  13821. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13822. const n = transformedNormalWorld;
  13823. context.backdrop = getIBLVolumeRefraction(
  13824. n,
  13825. v,
  13826. roughness,
  13827. diffuseColor,
  13828. specularColor,
  13829. specularF90, // specularF90
  13830. position, // positionWorld
  13831. modelWorldMatrix, // modelMatrix
  13832. cameraViewMatrix, // viewMatrix
  13833. cameraProjectionMatrix, // projMatrix
  13834. ior,
  13835. thickness,
  13836. attenuationColor,
  13837. attenuationDistance,
  13838. this.dispersion ? dispersion : null
  13839. );
  13840. context.backdropAlpha = transmission;
  13841. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13842. }
  13843. }
  13844. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13845. // Approximates multi-scattering in order to preserve energy.
  13846. // http://www.jcgt.org/published/0008/01/03/
  13847. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13848. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13849. const fab = DFGApprox( { roughness, dotNV } );
  13850. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13851. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13852. const Ess = fab.x.add( fab.y );
  13853. const Ems = Ess.oneMinus();
  13854. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13855. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13856. singleScatter.addAssign( FssEss );
  13857. multiScatter.addAssign( Fms.mul( Ems ) );
  13858. }
  13859. /**
  13860. * Implements the direct light.
  13861. *
  13862. * @param {Object} input - The input data.
  13863. * @param {StackNode} stack - The current stack.
  13864. * @param {NodeBuilder} builder - The current node builder.
  13865. */
  13866. direct( { lightDirection, lightColor, reflectedLight } ) {
  13867. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13868. const irradiance = dotNL.mul( lightColor );
  13869. if ( this.sheen === true ) {
  13870. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13871. }
  13872. if ( this.clearcoat === true ) {
  13873. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13874. const ccIrradiance = dotNLcc.mul( lightColor );
  13875. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13876. }
  13877. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13878. 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 } ) ) );
  13879. }
  13880. /**
  13881. * This method is intended for implementing the direct light term for
  13882. * rect area light nodes.
  13883. *
  13884. * @param {Object} input - The input data.
  13885. * @param {StackNode} stack - The current stack.
  13886. * @param {NodeBuilder} builder - The current node builder.
  13887. */
  13888. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13889. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13890. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13891. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13892. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13893. const N = transformedNormalView;
  13894. const V = positionViewDirection;
  13895. const P = positionView.toVar();
  13896. const uv = LTC_Uv( { N, V, roughness } );
  13897. const t1 = ltc_1.sample( uv ).toVar();
  13898. const t2 = ltc_2.sample( uv ).toVar();
  13899. const mInv = mat3(
  13900. vec3( t1.x, 0, t1.y ),
  13901. vec3( 0, 1, 0 ),
  13902. vec3( t1.z, 0, t1.w )
  13903. ).toVar();
  13904. // LTC Fresnel Approximation by Stephen Hill
  13905. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13906. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13907. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13908. 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 } ) ) );
  13909. }
  13910. /**
  13911. * Implements the indirect lighting.
  13912. *
  13913. * @param {ContextNode} context - The current node context.
  13914. * @param {StackNode} stack - The current stack.
  13915. * @param {NodeBuilder} builder - The current node builder.
  13916. */
  13917. indirect( context, stack, builder ) {
  13918. this.indirectDiffuse( context, stack, builder );
  13919. this.indirectSpecular( context, stack, builder );
  13920. this.ambientOcclusion( context, stack, builder );
  13921. }
  13922. /**
  13923. * Implements the indirect diffuse term.
  13924. *
  13925. * @param {ContextNode} input - The current node context.
  13926. * @param {StackNode} stack - The current stack.
  13927. * @param {NodeBuilder} builder - The current node builder.
  13928. */
  13929. indirectDiffuse( { irradiance, reflectedLight } ) {
  13930. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13931. }
  13932. /**
  13933. * Implements the indirect specular term.
  13934. *
  13935. * @param {ContextNode} input - The current node context.
  13936. * @param {StackNode} stack - The current stack.
  13937. * @param {NodeBuilder} builder - The current node builder.
  13938. */
  13939. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13940. if ( this.sheen === true ) {
  13941. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13942. sheen,
  13943. IBLSheenBRDF( {
  13944. normal: transformedNormalView,
  13945. viewDir: positionViewDirection,
  13946. roughness: sheenRoughness
  13947. } )
  13948. ) );
  13949. }
  13950. if ( this.clearcoat === true ) {
  13951. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13952. const clearcoatEnv = EnvironmentBRDF( {
  13953. dotNV: dotNVcc,
  13954. specularColor: clearcoatF0,
  13955. specularF90: clearcoatF90,
  13956. roughness: clearcoatRoughness
  13957. } );
  13958. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13959. }
  13960. // Both indirect specular and indirect diffuse light accumulate here
  13961. const singleScattering = vec3().toVar( 'singleScattering' );
  13962. const multiScattering = vec3().toVar( 'multiScattering' );
  13963. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13964. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13965. const totalScattering = singleScattering.add( multiScattering );
  13966. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13967. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13968. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13969. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13970. }
  13971. /**
  13972. * Implements the ambient occlusion term.
  13973. *
  13974. * @param {ContextNode} input - The current node context.
  13975. * @param {StackNode} stack - The current stack.
  13976. * @param {NodeBuilder} builder - The current node builder.
  13977. */
  13978. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13979. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13980. const aoNV = dotNV.add( ambientOcclusion );
  13981. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13982. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13983. if ( this.clearcoat === true ) {
  13984. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13985. }
  13986. if ( this.sheen === true ) {
  13987. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13988. }
  13989. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13990. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13991. }
  13992. /**
  13993. * Used for final lighting accumulations depending on the requested features.
  13994. *
  13995. * @param {ContextNode} context - The current node context.
  13996. * @param {StackNode} stack - The current stack.
  13997. * @param {NodeBuilder} builder - The current node builder.
  13998. */
  13999. finish( context ) {
  14000. const { outgoingLight } = context;
  14001. if ( this.clearcoat === true ) {
  14002. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14003. const Fcc = F_Schlick( {
  14004. dotVH: dotNVcc,
  14005. f0: clearcoatF0,
  14006. f90: clearcoatF90
  14007. } );
  14008. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14009. outgoingLight.assign( clearcoatLight );
  14010. }
  14011. if ( this.sheen === true ) {
  14012. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14013. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14014. outgoingLight.assign( sheenLight );
  14015. }
  14016. }
  14017. }
  14018. // These defines must match with PMREMGenerator
  14019. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14020. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  14021. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14022. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  14023. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14024. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14025. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14026. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14027. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14028. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14029. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14030. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14031. // These shader functions convert between the UV coordinates of a single face of
  14032. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14033. // sampling a textureCube (not generally normalized ).
  14034. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14035. const absDirection = vec3( abs( direction ) ).toVar();
  14036. const face = float( - 1.0 ).toVar();
  14037. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14038. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14039. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14040. } ).Else( () => {
  14041. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14042. } );
  14043. } ).Else( () => {
  14044. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14045. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14046. } ).Else( () => {
  14047. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14048. } );
  14049. } );
  14050. return face;
  14051. } ).setLayout( {
  14052. name: 'getFace',
  14053. type: 'float',
  14054. inputs: [
  14055. { name: 'direction', type: 'vec3' }
  14056. ]
  14057. } );
  14058. // RH coordinate system; PMREM face-indexing convention
  14059. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14060. const uv = vec2().toVar();
  14061. If( face.equal( 0.0 ), () => {
  14062. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14063. } ).ElseIf( face.equal( 1.0 ), () => {
  14064. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14065. } ).ElseIf( face.equal( 2.0 ), () => {
  14066. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14067. } ).ElseIf( face.equal( 3.0 ), () => {
  14068. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14069. } ).ElseIf( face.equal( 4.0 ), () => {
  14070. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14071. } ).Else( () => {
  14072. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14073. } );
  14074. return mul( 0.5, uv.add( 1.0 ) );
  14075. } ).setLayout( {
  14076. name: 'getUV',
  14077. type: 'vec2',
  14078. inputs: [
  14079. { name: 'direction', type: 'vec3' },
  14080. { name: 'face', type: 'float' }
  14081. ]
  14082. } );
  14083. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14084. const mip = float( 0.0 ).toVar();
  14085. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14086. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14087. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14088. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14089. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14090. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14091. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14092. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14093. } ).Else( () => {
  14094. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14095. } );
  14096. return mip;
  14097. } ).setLayout( {
  14098. name: 'roughnessToMip',
  14099. type: 'float',
  14100. inputs: [
  14101. { name: 'roughness', type: 'float' }
  14102. ]
  14103. } );
  14104. // RH coordinate system; PMREM face-indexing convention
  14105. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14106. const uv = uv_immutable.toVar();
  14107. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14108. const direction = vec3( uv, 1.0 ).toVar();
  14109. If( face.equal( 0.0 ), () => {
  14110. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14111. } ).ElseIf( face.equal( 1.0 ), () => {
  14112. direction.assign( direction.xzy );
  14113. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14114. } ).ElseIf( face.equal( 2.0 ), () => {
  14115. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14116. } ).ElseIf( face.equal( 3.0 ), () => {
  14117. direction.assign( direction.zyx );
  14118. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14119. } ).ElseIf( face.equal( 4.0 ), () => {
  14120. direction.assign( direction.xzy );
  14121. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14122. } ).ElseIf( face.equal( 5.0 ), () => {
  14123. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14124. } );
  14125. return direction;
  14126. } ).setLayout( {
  14127. name: 'getDirection',
  14128. type: 'vec3',
  14129. inputs: [
  14130. { name: 'uv', type: 'vec2' },
  14131. { name: 'face', type: 'float' }
  14132. ]
  14133. } );
  14134. //
  14135. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14136. const roughness = float( roughness_immutable );
  14137. const sampleDir = vec3( sampleDir_immutable );
  14138. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14139. const mipF = fract( mip );
  14140. const mipInt = floor( mip );
  14141. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14142. If( mipF.notEqual( 0.0 ), () => {
  14143. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14144. color0.assign( mix( color0, color1, mipF ) );
  14145. } );
  14146. return color0;
  14147. } );
  14148. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14149. const mipInt = float( mipInt_immutable ).toVar();
  14150. const direction = vec3( direction_immutable );
  14151. const face = float( getFace( direction ) ).toVar();
  14152. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14153. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14154. const faceSize = float( exp2( mipInt ) ).toVar();
  14155. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14156. If( face.greaterThan( 2.0 ), () => {
  14157. uv.y.addAssign( faceSize );
  14158. face.subAssign( 3.0 );
  14159. } );
  14160. uv.x.addAssign( face.mul( faceSize ) );
  14161. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14162. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14163. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14164. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14165. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14166. } );
  14167. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14168. const cosTheta = cos( theta );
  14169. // Rodrigues' axis-angle rotation
  14170. const sampleDirection = outputDirection.mul( cosTheta )
  14171. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14172. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14173. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14174. } );
  14175. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14176. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14177. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14178. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14179. } );
  14180. axis.assign( normalize( axis ) );
  14181. const gl_FragColor = vec3().toVar();
  14182. 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 } ) ) );
  14183. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14184. If( i.greaterThanEqual( samples ), () => {
  14185. Break();
  14186. } );
  14187. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14188. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14189. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14190. } );
  14191. return vec4( gl_FragColor, 1 );
  14192. } );
  14193. /** @module PMREMNode **/
  14194. let _generator = null;
  14195. const _cache = new WeakMap();
  14196. /**
  14197. * Generates the cubeUV size based on the given image height.
  14198. *
  14199. * @private
  14200. * @param {Number} imageHeight - The image height.
  14201. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14202. */
  14203. function _generateCubeUVSize( imageHeight ) {
  14204. const maxMip = Math.log2( imageHeight ) - 2;
  14205. const texelHeight = 1.0 / imageHeight;
  14206. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14207. return { texelWidth, texelHeight, maxMip };
  14208. }
  14209. /**
  14210. * Generates a PMREM from the given texture .
  14211. *
  14212. * @private
  14213. * @param {Texture} texture - The texture to create the PMREM for.
  14214. * @return {Texture} The PMREM.
  14215. */
  14216. function _getPMREMFromTexture( texture ) {
  14217. let cacheTexture = _cache.get( texture );
  14218. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14219. if ( pmremVersion !== texture.pmremVersion ) {
  14220. const image = texture.image;
  14221. if ( texture.isCubeTexture ) {
  14222. if ( isCubeMapReady( image ) ) {
  14223. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14224. } else {
  14225. return null;
  14226. }
  14227. } else {
  14228. if ( isEquirectangularMapReady( image ) ) {
  14229. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14230. } else {
  14231. return null;
  14232. }
  14233. }
  14234. cacheTexture.pmremVersion = texture.pmremVersion;
  14235. _cache.set( texture, cacheTexture );
  14236. }
  14237. return cacheTexture.texture;
  14238. }
  14239. /**
  14240. * This node represents a PMREM which is a special type of preprocessed
  14241. * environment map intended for PBR materials.
  14242. *
  14243. * ```js
  14244. * const material = new MeshStandardNodeMaterial();
  14245. * material.envNode = pmremTexture( envMap );
  14246. * ```
  14247. *
  14248. * @augments TempNode
  14249. */
  14250. class PMREMNode extends TempNode {
  14251. static get type() {
  14252. return 'PMREMNode';
  14253. }
  14254. /**
  14255. * Constructs a new function overloading node.
  14256. *
  14257. * @param {Texture} value - The input texture.
  14258. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14259. * @param {Node<float>} [levelNode=null] - The level node.
  14260. */
  14261. constructor( value, uvNode = null, levelNode = null ) {
  14262. super( 'vec3' );
  14263. /**
  14264. * Reference to the input texture.
  14265. *
  14266. * @private
  14267. * @type {Texture}
  14268. */
  14269. this._value = value;
  14270. /**
  14271. * Reference to the generated PMREM.
  14272. *
  14273. * @private
  14274. * @type {Texture | null}
  14275. * @default null
  14276. */
  14277. this._pmrem = null;
  14278. /**
  14279. * The uv node.
  14280. *
  14281. * @type {Node<vec2>}
  14282. */
  14283. this.uvNode = uvNode;
  14284. /**
  14285. * The level node.
  14286. *
  14287. * @type {Node<float>}
  14288. */
  14289. this.levelNode = levelNode;
  14290. /**
  14291. * Reference to a PMREM generator.
  14292. *
  14293. * @private
  14294. * @type {PMREMGenerator}
  14295. * @default null
  14296. */
  14297. this._generator = null;
  14298. const defaultTexture = new Texture();
  14299. defaultTexture.isRenderTargetTexture = true;
  14300. /**
  14301. * The texture node holding the generated PMREM.
  14302. *
  14303. * @private
  14304. * @type {TextureNode}
  14305. */
  14306. this._texture = texture( defaultTexture );
  14307. /**
  14308. * A uniform representing the PMREM's width.
  14309. *
  14310. * @private
  14311. * @type {UniformNode<float>}
  14312. */
  14313. this._width = uniform( 0 );
  14314. /**
  14315. * A uniform representing the PMREM's height.
  14316. *
  14317. * @private
  14318. * @type {UniformNode<float>}
  14319. */
  14320. this._height = uniform( 0 );
  14321. /**
  14322. * A uniform representing the PMREM's max Mip.
  14323. *
  14324. * @private
  14325. * @type {UniformNode<float>}
  14326. */
  14327. this._maxMip = uniform( 0 );
  14328. /**
  14329. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14330. *
  14331. * @type {String}
  14332. * @default 'render'
  14333. */
  14334. this.updateBeforeType = NodeUpdateType.RENDER;
  14335. }
  14336. set value( value ) {
  14337. this._value = value;
  14338. this._pmrem = null;
  14339. }
  14340. /**
  14341. * The node's texture value.
  14342. *
  14343. * @type {Texture}
  14344. */
  14345. get value() {
  14346. return this._value;
  14347. }
  14348. /**
  14349. * Uses the given PMREM texture to update internal values.
  14350. *
  14351. * @param {Texture} texture - The PMREM texture.
  14352. */
  14353. updateFromTexture( texture ) {
  14354. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14355. this._texture.value = texture;
  14356. this._width.value = cubeUVSize.texelWidth;
  14357. this._height.value = cubeUVSize.texelHeight;
  14358. this._maxMip.value = cubeUVSize.maxMip;
  14359. }
  14360. updateBefore() {
  14361. let pmrem = this._pmrem;
  14362. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14363. const texture = this._value;
  14364. if ( pmremVersion !== texture.pmremVersion ) {
  14365. if ( texture.isPMREMTexture === true ) {
  14366. pmrem = texture;
  14367. } else {
  14368. pmrem = _getPMREMFromTexture( texture );
  14369. }
  14370. if ( pmrem !== null ) {
  14371. this._pmrem = pmrem;
  14372. this.updateFromTexture( pmrem );
  14373. }
  14374. }
  14375. }
  14376. setup( builder ) {
  14377. if ( _generator === null ) {
  14378. _generator = builder.createPMREMGenerator();
  14379. }
  14380. //
  14381. this.updateBefore( builder );
  14382. //
  14383. let uvNode = this.uvNode;
  14384. if ( uvNode === null && builder.context.getUV ) {
  14385. uvNode = builder.context.getUV( this );
  14386. }
  14387. //
  14388. const texture = this.value;
  14389. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14390. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14391. }
  14392. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14393. //
  14394. let levelNode = this.levelNode;
  14395. if ( levelNode === null && builder.context.getTextureLevel ) {
  14396. levelNode = builder.context.getTextureLevel( this );
  14397. }
  14398. //
  14399. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14400. }
  14401. }
  14402. /**
  14403. * Returns `true` if the given cube map image has been fully loaded.
  14404. *
  14405. * @private
  14406. * @param {Array<(Image|Object)>} image - The cube map image.
  14407. * @return {Boolean} Whether the given cube map is ready or not.
  14408. */
  14409. function isCubeMapReady( image ) {
  14410. if ( image === null || image === undefined ) return false;
  14411. let count = 0;
  14412. const length = 6;
  14413. for ( let i = 0; i < length; i ++ ) {
  14414. if ( image[ i ] !== undefined ) count ++;
  14415. }
  14416. return count === length;
  14417. }
  14418. /**
  14419. * Returns `true` if the given equirectangular image has been fully loaded.
  14420. *
  14421. * @private
  14422. * @param {(Image|Object)} image - The equirectangular image.
  14423. * @return {Boolean} Whether the given cube map is ready or not.
  14424. */
  14425. function isEquirectangularMapReady( image ) {
  14426. if ( image === null || image === undefined ) return false;
  14427. return image.height > 0;
  14428. }
  14429. /**
  14430. * TSL function for creating a PMREM node.
  14431. *
  14432. * @function
  14433. * @param {Texture} value - The input texture.
  14434. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14435. * @param {Node<float>} [levelNode=null] - The level node.
  14436. * @returns {PMREMNode}
  14437. */
  14438. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14439. const _envNodeCache = new WeakMap();
  14440. /**
  14441. * Represents a physical model for Image-based lighting (IBL). The environment
  14442. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14443. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14444. *
  14445. * @augments LightingNode
  14446. */
  14447. class EnvironmentNode extends LightingNode {
  14448. static get type() {
  14449. return 'EnvironmentNode';
  14450. }
  14451. /**
  14452. * Constructs a new environment node.
  14453. *
  14454. * @param {Node} [envNode=null] - A node representing the environment.
  14455. */
  14456. constructor( envNode = null ) {
  14457. super();
  14458. /**
  14459. * A node representing the environment.
  14460. *
  14461. * @type {Node?}
  14462. * @default null
  14463. */
  14464. this.envNode = envNode;
  14465. }
  14466. setup( builder ) {
  14467. const { material } = builder;
  14468. let envNode = this.envNode;
  14469. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14470. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14471. let cacheEnvNode = _envNodeCache.get( value );
  14472. if ( cacheEnvNode === undefined ) {
  14473. cacheEnvNode = pmremTexture( value );
  14474. _envNodeCache.set( value, cacheEnvNode );
  14475. }
  14476. envNode = cacheEnvNode;
  14477. }
  14478. //
  14479. const envMap = material.envMap;
  14480. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14481. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14482. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14483. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14484. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14485. const isolateRadiance = cache( radiance );
  14486. const isolateIrradiance = cache( irradiance );
  14487. //
  14488. builder.context.radiance.addAssign( isolateRadiance );
  14489. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14490. //
  14491. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14492. if ( clearcoatRadiance ) {
  14493. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14494. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14495. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14496. }
  14497. }
  14498. }
  14499. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14500. let reflectVec = null;
  14501. return {
  14502. getUV: () => {
  14503. if ( reflectVec === null ) {
  14504. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14505. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14506. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14507. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14508. }
  14509. return reflectVec;
  14510. },
  14511. getTextureLevel: () => {
  14512. return roughnessNode;
  14513. }
  14514. };
  14515. };
  14516. const createIrradianceContext = ( normalWorldNode ) => {
  14517. return {
  14518. getUV: () => {
  14519. return normalWorldNode;
  14520. },
  14521. getTextureLevel: () => {
  14522. return float( 1.0 );
  14523. }
  14524. };
  14525. };
  14526. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14527. /**
  14528. * Node material version of `MeshStandardMaterial`.
  14529. *
  14530. * @augments NodeMaterial
  14531. */
  14532. class MeshStandardNodeMaterial extends NodeMaterial {
  14533. static get type() {
  14534. return 'MeshStandardNodeMaterial';
  14535. }
  14536. /**
  14537. * Constructs a new mesh standard node material.
  14538. *
  14539. * @param {Object?} parameters - The configuration parameter.
  14540. */
  14541. constructor( parameters ) {
  14542. super();
  14543. /**
  14544. * This flag can be used for type testing.
  14545. *
  14546. * @type {Boolean}
  14547. * @readonly
  14548. * @default true
  14549. */
  14550. this.isMeshStandardNodeMaterial = true;
  14551. /**
  14552. * Set to `true` because standard materials react on lights.
  14553. *
  14554. * @type {Boolean}
  14555. * @default true
  14556. */
  14557. this.lights = true;
  14558. /**
  14559. * The emissive color of standard materials is by default inferred from the `emissive`,
  14560. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14561. * overwrite the default and define the emissive color with a node instead.
  14562. *
  14563. * If you don't want to overwrite the emissive color but modify the existing
  14564. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14565. *
  14566. * @type {Node<vec3>?}
  14567. * @default null
  14568. */
  14569. this.emissiveNode = null;
  14570. /**
  14571. * The metalness of standard materials is by default inferred from the `metalness`,
  14572. * and `metalnessMap` properties. This node property allows to
  14573. * overwrite the default and define the metalness with a node instead.
  14574. *
  14575. * If you don't want to overwrite the metalness but modify the existing
  14576. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14577. *
  14578. * @type {Node<float>?}
  14579. * @default null
  14580. */
  14581. this.metalnessNode = null;
  14582. /**
  14583. * The roughness of standard materials is by default inferred from the `roughness`,
  14584. * and `roughnessMap` properties. This node property allows to
  14585. * overwrite the default and define the roughness with a node instead.
  14586. *
  14587. * If you don't want to overwrite the roughness but modify the existing
  14588. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14589. *
  14590. * @type {Node<float>?}
  14591. * @default null
  14592. */
  14593. this.roughnessNode = null;
  14594. this.setDefaultValues( _defaultValues$6 );
  14595. this.setValues( parameters );
  14596. }
  14597. /**
  14598. * Overwritten since this type of material uses {@link EnvironmentNode}
  14599. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14600. * method honors `Scene.environment`.
  14601. *
  14602. * @param {NodeBuilder} builder - The current node builder.
  14603. * @return {EnvironmentNode<vec3>?} The environment node.
  14604. */
  14605. setupEnvironment( builder ) {
  14606. let envNode = super.setupEnvironment( builder );
  14607. if ( envNode === null && builder.environmentNode ) {
  14608. envNode = builder.environmentNode;
  14609. }
  14610. return envNode ? new EnvironmentNode( envNode ) : null;
  14611. }
  14612. /**
  14613. * Setups the lighting model.
  14614. *
  14615. * @return {PhysicalLightingModel} The lighting model.
  14616. */
  14617. setupLightingModel( /*builder*/ ) {
  14618. return new PhysicalLightingModel();
  14619. }
  14620. /**
  14621. * Setups the specular related node variables.
  14622. */
  14623. setupSpecular() {
  14624. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14625. specularColor.assign( specularColorNode );
  14626. specularF90.assign( 1.0 );
  14627. }
  14628. /**
  14629. * Setups the standard specific node variables.
  14630. *
  14631. * @param {NodeBuilder} builder - The current node builder.
  14632. */
  14633. setupVariants() {
  14634. // METALNESS
  14635. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14636. metalness.assign( metalnessNode );
  14637. // ROUGHNESS
  14638. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14639. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14640. roughness.assign( roughnessNode );
  14641. // SPECULAR COLOR
  14642. this.setupSpecular();
  14643. // DIFFUSE COLOR
  14644. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14645. }
  14646. copy( source ) {
  14647. this.emissiveNode = source.emissiveNode;
  14648. this.metalnessNode = source.metalnessNode;
  14649. this.roughnessNode = source.roughnessNode;
  14650. return super.copy( source );
  14651. }
  14652. }
  14653. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14654. /**
  14655. * Node material version of `MeshPhysicalMaterial`.
  14656. *
  14657. * @augments MeshStandardNodeMaterial
  14658. */
  14659. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14660. static get type() {
  14661. return 'MeshPhysicalNodeMaterial';
  14662. }
  14663. /**
  14664. * Constructs a new mesh physical node material.
  14665. *
  14666. * @param {Object?} parameters - The configuration parameter.
  14667. */
  14668. constructor( parameters ) {
  14669. super();
  14670. /**
  14671. * This flag can be used for type testing.
  14672. *
  14673. * @type {Boolean}
  14674. * @readonly
  14675. * @default true
  14676. */
  14677. this.isMeshPhysicalNodeMaterial = true;
  14678. /**
  14679. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14680. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14681. * and define the clearcoat with a node instead.
  14682. *
  14683. * If you don't want to overwrite the clearcoat but modify the existing
  14684. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14685. *
  14686. * @type {Node<float>?}
  14687. * @default null
  14688. */
  14689. this.clearcoatNode = null;
  14690. /**
  14691. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14692. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14693. * and define the clearcoat roughness with a node instead.
  14694. *
  14695. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14696. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14697. *
  14698. * @type {Node<float>?}
  14699. * @default null
  14700. */
  14701. this.clearcoatRoughnessNode = null;
  14702. /**
  14703. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14704. * property. This node property allows to overwrite the default
  14705. * and define the clearcoat normal with a node instead.
  14706. *
  14707. * If you don't want to overwrite the clearcoat normal but modify the existing
  14708. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14709. *
  14710. * @type {Node<vec3>?}
  14711. * @default null
  14712. */
  14713. this.clearcoatNormalNode = null;
  14714. /**
  14715. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14716. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14717. * and define the sheen with a node instead.
  14718. *
  14719. * If you don't want to overwrite the sheen but modify the existing
  14720. * value instead, use {@link module:MaterialNode.materialSheen}.
  14721. *
  14722. * @type {Node<vec3>?}
  14723. * @default null
  14724. */
  14725. this.sheenNode = null;
  14726. /**
  14727. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14728. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14729. * and define the sheen roughness with a node instead.
  14730. *
  14731. * If you don't want to overwrite the sheen roughness but modify the existing
  14732. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14733. *
  14734. * @type {Node<float>?}
  14735. * @default null
  14736. */
  14737. this.sheenRoughnessNode = null;
  14738. /**
  14739. * The iridescence of physical materials is by default inferred from the `iridescence`
  14740. * property. This node property allows to overwrite the default
  14741. * and define the iridescence with a node instead.
  14742. *
  14743. * If you don't want to overwrite the iridescence but modify the existing
  14744. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14745. *
  14746. * @type {Node<float>?}
  14747. * @default null
  14748. */
  14749. this.iridescenceNode = null;
  14750. /**
  14751. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14752. * property. This node property allows to overwrite the default
  14753. * and define the iridescence IOR with a node instead.
  14754. *
  14755. * If you don't want to overwrite the iridescence IOR but modify the existing
  14756. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14757. *
  14758. * @type {Node<float>?}
  14759. * @default null
  14760. */
  14761. this.iridescenceIORNode = null;
  14762. /**
  14763. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14764. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14765. * and define the iridescence thickness with a node instead.
  14766. *
  14767. * If you don't want to overwrite the iridescence thickness but modify the existing
  14768. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14769. *
  14770. * @type {Node<float>?}
  14771. * @default null
  14772. */
  14773. this.iridescenceThicknessNode = null;
  14774. /**
  14775. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14776. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14777. * and define the specular intensity with a node instead.
  14778. *
  14779. * If you don't want to overwrite the specular intensity but modify the existing
  14780. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14781. *
  14782. * @type {Node<float>?}
  14783. * @default null
  14784. */
  14785. this.specularIntensityNode = null;
  14786. /**
  14787. * The specular color of physical materials is by default inferred from the `specularColor`
  14788. * and `specularColorMap` properties. This node property allows to overwrite the default
  14789. * and define the specular color with a node instead.
  14790. *
  14791. * If you don't want to overwrite the specular color but modify the existing
  14792. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14793. *
  14794. * @type {Node<vec3>?}
  14795. * @default null
  14796. */
  14797. this.specularColorNode = null;
  14798. /**
  14799. * The ior of physical materials is by default inferred from the `ior`
  14800. * property. This node property allows to overwrite the default
  14801. * and define the ior with a node instead.
  14802. *
  14803. * If you don't want to overwrite the ior but modify the existing
  14804. * value instead, use {@link module:MaterialNode.materialIOR}.
  14805. *
  14806. * @type {Node<float>?}
  14807. * @default null
  14808. */
  14809. this.iorNode = null;
  14810. /**
  14811. * The transmission of physical materials is by default inferred from the `transmission` and
  14812. * `transmissionMap` properties. This node property allows to overwrite the default
  14813. * and define the transmission with a node instead.
  14814. *
  14815. * If you don't want to overwrite the transmission but modify the existing
  14816. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14817. *
  14818. * @type {Node<float>?}
  14819. * @default null
  14820. */
  14821. this.transmissionNode = null;
  14822. /**
  14823. * The thickness of physical materials is by default inferred from the `thickness` and
  14824. * `thicknessMap` properties. This node property allows to overwrite the default
  14825. * and define the thickness with a node instead.
  14826. *
  14827. * If you don't want to overwrite the thickness but modify the existing
  14828. * value instead, use {@link module:MaterialNode.materialThickness}.
  14829. *
  14830. * @type {Node<float>?}
  14831. * @default null
  14832. */
  14833. this.thicknessNode = null;
  14834. /**
  14835. * The attenuation distance of physical materials is by default inferred from the
  14836. * `attenuationDistance` property. This node property allows to overwrite the default
  14837. * and define the attenuation distance with a node instead.
  14838. *
  14839. * If you don't want to overwrite the attenuation distance but modify the existing
  14840. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14841. *
  14842. * @type {Node<float>?}
  14843. * @default null
  14844. */
  14845. this.attenuationDistanceNode = null;
  14846. /**
  14847. * The attenuation color of physical materials is by default inferred from the
  14848. * `attenuationColor` property. This node property allows to overwrite the default
  14849. * and define the attenuation color with a node instead.
  14850. *
  14851. * If you don't want to overwrite the attenuation color but modify the existing
  14852. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14853. *
  14854. * @type {Node<vec3>?}
  14855. * @default null
  14856. */
  14857. this.attenuationColorNode = null;
  14858. /**
  14859. * The dispersion of physical materials is by default inferred from the
  14860. * `dispersion` property. This node property allows to overwrite the default
  14861. * and define the dispersion with a node instead.
  14862. *
  14863. * If you don't want to overwrite the dispersion but modify the existing
  14864. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14865. *
  14866. * @type {Node<float>?}
  14867. * @default null
  14868. */
  14869. this.dispersionNode = null;
  14870. /**
  14871. * The anisotropy of physical materials is by default inferred from the
  14872. * `anisotropy` property. This node property allows to overwrite the default
  14873. * and define the anisotropy with a node instead.
  14874. *
  14875. * If you don't want to overwrite the anisotropy but modify the existing
  14876. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14877. *
  14878. * @type {Node<float>?}
  14879. * @default null
  14880. */
  14881. this.anisotropyNode = null;
  14882. this.setDefaultValues( _defaultValues$5 );
  14883. this.setValues( parameters );
  14884. }
  14885. /**
  14886. * Whether the lighting model should use clearcoat or not.
  14887. *
  14888. * @type {Boolean}
  14889. * @default true
  14890. */
  14891. get useClearcoat() {
  14892. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14893. }
  14894. /**
  14895. * Whether the lighting model should use iridescence or not.
  14896. *
  14897. * @type {Boolean}
  14898. * @default true
  14899. */
  14900. get useIridescence() {
  14901. return this.iridescence > 0 || this.iridescenceNode !== null;
  14902. }
  14903. /**
  14904. * Whether the lighting model should use sheen or not.
  14905. *
  14906. * @type {Boolean}
  14907. * @default true
  14908. */
  14909. get useSheen() {
  14910. return this.sheen > 0 || this.sheenNode !== null;
  14911. }
  14912. /**
  14913. * Whether the lighting model should use anisotropy or not.
  14914. *
  14915. * @type {Boolean}
  14916. * @default true
  14917. */
  14918. get useAnisotropy() {
  14919. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14920. }
  14921. /**
  14922. * Whether the lighting model should use transmission or not.
  14923. *
  14924. * @type {Boolean}
  14925. * @default true
  14926. */
  14927. get useTransmission() {
  14928. return this.transmission > 0 || this.transmissionNode !== null;
  14929. }
  14930. /**
  14931. * Whether the lighting model should use dispersion or not.
  14932. *
  14933. * @type {Boolean}
  14934. * @default true
  14935. */
  14936. get useDispersion() {
  14937. return this.dispersion > 0 || this.dispersionNode !== null;
  14938. }
  14939. /**
  14940. * Setups the specular related node variables.
  14941. */
  14942. setupSpecular() {
  14943. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14944. ior.assign( iorNode );
  14945. 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 ) );
  14946. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14947. }
  14948. /**
  14949. * Setups the lighting model.
  14950. *
  14951. * @return {PhysicalLightingModel} The lighting model.
  14952. */
  14953. setupLightingModel( /*builder*/ ) {
  14954. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14955. }
  14956. /**
  14957. * Setups the physical specific node variables.
  14958. *
  14959. * @param {NodeBuilder} builder - The current node builder.
  14960. */
  14961. setupVariants( builder ) {
  14962. super.setupVariants( builder );
  14963. // CLEARCOAT
  14964. if ( this.useClearcoat ) {
  14965. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14966. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14967. clearcoat.assign( clearcoatNode );
  14968. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14969. }
  14970. // SHEEN
  14971. if ( this.useSheen ) {
  14972. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14973. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14974. sheen.assign( sheenNode );
  14975. sheenRoughness.assign( sheenRoughnessNode );
  14976. }
  14977. // IRIDESCENCE
  14978. if ( this.useIridescence ) {
  14979. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14980. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14981. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14982. iridescence.assign( iridescenceNode );
  14983. iridescenceIOR.assign( iridescenceIORNode );
  14984. iridescenceThickness.assign( iridescenceThicknessNode );
  14985. }
  14986. // ANISOTROPY
  14987. if ( this.useAnisotropy ) {
  14988. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14989. anisotropy.assign( anisotropyV.length() );
  14990. If( anisotropy.equal( 0.0 ), () => {
  14991. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14992. } ).Else( () => {
  14993. anisotropyV.divAssign( vec2( anisotropy ) );
  14994. anisotropy.assign( anisotropy.saturate() );
  14995. } );
  14996. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14997. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14998. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14999. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15000. }
  15001. // TRANSMISSION
  15002. if ( this.useTransmission ) {
  15003. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15004. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15005. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15006. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15007. transmission.assign( transmissionNode );
  15008. thickness.assign( thicknessNode );
  15009. attenuationDistance.assign( attenuationDistanceNode );
  15010. attenuationColor.assign( attenuationColorNode );
  15011. if ( this.useDispersion ) {
  15012. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15013. dispersion.assign( dispersionNode );
  15014. }
  15015. }
  15016. }
  15017. /**
  15018. * Setups the clearcoat normal node.
  15019. *
  15020. * @return {Node<vec3>} The clearcoat normal.
  15021. */
  15022. setupClearcoatNormal() {
  15023. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15024. }
  15025. setup( builder ) {
  15026. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15027. super.setup( builder );
  15028. }
  15029. copy( source ) {
  15030. this.clearcoatNode = source.clearcoatNode;
  15031. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15032. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15033. this.sheenNode = source.sheenNode;
  15034. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15035. this.iridescenceNode = source.iridescenceNode;
  15036. this.iridescenceIORNode = source.iridescenceIORNode;
  15037. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15038. this.specularIntensityNode = source.specularIntensityNode;
  15039. this.specularColorNode = source.specularColorNode;
  15040. this.transmissionNode = source.transmissionNode;
  15041. this.thicknessNode = source.thicknessNode;
  15042. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15043. this.attenuationColorNode = source.attenuationColorNode;
  15044. this.dispersionNode = source.dispersionNode;
  15045. this.anisotropyNode = source.anisotropyNode;
  15046. return super.copy( source );
  15047. }
  15048. }
  15049. /** @module MeshSSSNodeMaterial **/
  15050. /**
  15051. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15052. *
  15053. * @augments PhysicalLightingModel
  15054. */
  15055. class SSSLightingModel extends PhysicalLightingModel {
  15056. /**
  15057. * Constructs a new physical lighting model.
  15058. *
  15059. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15060. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15061. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15062. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15063. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15064. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15065. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15066. */
  15067. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15068. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15069. /**
  15070. * Whether the lighting model should use SSS or not.
  15071. *
  15072. * @type {Boolean}
  15073. * @default false
  15074. */
  15075. this.useSSS = sss;
  15076. }
  15077. /**
  15078. * Extends the default implementation with a SSS term.
  15079. *
  15080. * 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/}
  15081. *
  15082. * @param {Object} input - The input data.
  15083. * @param {StackNode} stack - The current stack.
  15084. * @param {NodeBuilder} builder - The current node builder.
  15085. */
  15086. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15087. if ( this.useSSS === true ) {
  15088. const material = builder.material;
  15089. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15090. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15091. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15092. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15093. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15094. }
  15095. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15096. }
  15097. }
  15098. /**
  15099. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15100. * that implements a Subsurface scattering (SSS) term.
  15101. *
  15102. * @augments MeshPhysicalNodeMaterial
  15103. */
  15104. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15105. static get type() {
  15106. return 'MeshSSSNodeMaterial';
  15107. }
  15108. /**
  15109. * Constructs a new mesh SSS node material.
  15110. *
  15111. * @param {Object?} parameters - The configuration parameter.
  15112. */
  15113. constructor( parameters ) {
  15114. super( parameters );
  15115. /**
  15116. * Represents the thickness color.
  15117. *
  15118. * @type {Node<vec3>?}
  15119. * @default null
  15120. */
  15121. this.thicknessColorNode = null;
  15122. /**
  15123. * Represents the distortion factor.
  15124. *
  15125. * @type {Node<float>?}
  15126. */
  15127. this.thicknessDistortionNode = float( 0.1 );
  15128. /**
  15129. * Represents the thickness ambient factor.
  15130. *
  15131. * @type {Node<float>?}
  15132. */
  15133. this.thicknessAmbientNode = float( 0.0 );
  15134. /**
  15135. * Represents the thickness attenuation.
  15136. *
  15137. * @type {Node<float>?}
  15138. */
  15139. this.thicknessAttenuationNode = float( .1 );
  15140. /**
  15141. * Represents the thickness power.
  15142. *
  15143. * @type {Node<float>?}
  15144. */
  15145. this.thicknessPowerNode = float( 2.0 );
  15146. /**
  15147. * Represents the thickness scale.
  15148. *
  15149. * @type {Node<float>?}
  15150. */
  15151. this.thicknessScaleNode = float( 10.0 );
  15152. }
  15153. /**
  15154. * Whether the lighting model should use SSS or not.
  15155. *
  15156. * @type {Boolean}
  15157. * @default true
  15158. */
  15159. get useSSS() {
  15160. return this.thicknessColorNode !== null;
  15161. }
  15162. /**
  15163. * Setups the lighting model.
  15164. *
  15165. * @return {SSSLightingModel} The lighting model.
  15166. */
  15167. setupLightingModel( /*builder*/ ) {
  15168. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15169. }
  15170. copy( source ) {
  15171. this.thicknessColorNode = source.thicknessColorNode;
  15172. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15173. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15174. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15175. this.thicknessPowerNode = source.thicknessPowerNode;
  15176. this.thicknessScaleNode = source.thicknessScaleNode;
  15177. return super.copy( source );
  15178. }
  15179. }
  15180. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15181. // dotNL will be from -1.0 to 1.0
  15182. const dotNL = normal.dot( lightDirection );
  15183. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15184. if ( builder.material.gradientMap ) {
  15185. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15186. return vec3( gradientMap.r );
  15187. } else {
  15188. const fw = coord.fwidth().mul( 0.5 );
  15189. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15190. }
  15191. } );
  15192. /**
  15193. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15194. *
  15195. * @augments LightingModel
  15196. */
  15197. class ToonLightingModel extends LightingModel {
  15198. /**
  15199. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15200. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15201. *
  15202. * @param {Object} input - The input data.
  15203. * @param {StackNode} stack - The current stack.
  15204. * @param {NodeBuilder} builder - The current node builder.
  15205. */
  15206. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15207. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15208. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15209. }
  15210. /**
  15211. * Implements the indirect lighting.
  15212. *
  15213. * @param {ContextNode} input - The current node context.
  15214. * @param {StackNode} stack - The current stack.
  15215. * @param {NodeBuilder} builder - The current node builder.
  15216. */
  15217. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15218. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15219. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15220. }
  15221. }
  15222. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15223. /**
  15224. * Node material version of `MeshToonMaterial`.
  15225. *
  15226. * @augments NodeMaterial
  15227. */
  15228. class MeshToonNodeMaterial extends NodeMaterial {
  15229. static get type() {
  15230. return 'MeshToonNodeMaterial';
  15231. }
  15232. /**
  15233. * Constructs a new mesh toon node material.
  15234. *
  15235. * @param {Object?} parameters - The configuration parameter.
  15236. */
  15237. constructor( parameters ) {
  15238. super();
  15239. /**
  15240. * This flag can be used for type testing.
  15241. *
  15242. * @type {Boolean}
  15243. * @readonly
  15244. * @default true
  15245. */
  15246. this.isMeshToonNodeMaterial = true;
  15247. /**
  15248. * Set to `true` because toon materials react on lights.
  15249. *
  15250. * @type {Boolean}
  15251. * @default true
  15252. */
  15253. this.lights = true;
  15254. this.setDefaultValues( _defaultValues$4 );
  15255. this.setValues( parameters );
  15256. }
  15257. /**
  15258. * Setups the lighting model.
  15259. *
  15260. * @return {ToonLightingModel} The lighting model.
  15261. */
  15262. setupLightingModel( /*builder*/ ) {
  15263. return new ToonLightingModel();
  15264. }
  15265. }
  15266. /** @module MatcapUVNode **/
  15267. /**
  15268. * Can be used to compute texture coordinates for projecting a
  15269. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15270. *
  15271. * @augments TempNode
  15272. */
  15273. class MatcapUVNode extends TempNode {
  15274. static get type() {
  15275. return 'MatcapUVNode';
  15276. }
  15277. /**
  15278. * Constructs a new matcap uv node.
  15279. */
  15280. constructor() {
  15281. super( 'vec2' );
  15282. }
  15283. setup() {
  15284. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15285. const y = positionViewDirection.cross( x );
  15286. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15287. }
  15288. }
  15289. /**
  15290. * TSL function for creating a matcap uv node.
  15291. *
  15292. * @function
  15293. * @returns {MatcapUVNode}
  15294. */
  15295. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15296. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15297. /**
  15298. * Node material version of `MeshMatcapMaterial`.
  15299. *
  15300. * @augments NodeMaterial
  15301. */
  15302. class MeshMatcapNodeMaterial extends NodeMaterial {
  15303. static get type() {
  15304. return 'MeshMatcapNodeMaterial';
  15305. }
  15306. /**
  15307. * Constructs a new mesh normal node material.
  15308. *
  15309. * @param {Object?} parameters - The configuration parameter.
  15310. */
  15311. constructor( parameters ) {
  15312. super();
  15313. /**
  15314. * This flag can be used for type testing.
  15315. *
  15316. * @type {Boolean}
  15317. * @readonly
  15318. * @default true
  15319. */
  15320. this.isMeshMatcapNodeMaterial = true;
  15321. this.setDefaultValues( _defaultValues$3 );
  15322. this.setValues( parameters );
  15323. }
  15324. /**
  15325. * Setups the matcap specific node variables.
  15326. *
  15327. * @param {NodeBuilder} builder - The current node builder.
  15328. */
  15329. setupVariants( builder ) {
  15330. const uv = matcapUV;
  15331. let matcapColor;
  15332. if ( builder.material.matcap ) {
  15333. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15334. } else {
  15335. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15336. }
  15337. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15338. }
  15339. }
  15340. /** @module RotateNode **/
  15341. /**
  15342. * Applies a rotation to the given position node.
  15343. *
  15344. * @augments TempNode
  15345. */
  15346. class RotateNode extends TempNode {
  15347. static get type() {
  15348. return 'RotateNode';
  15349. }
  15350. /**
  15351. * Constructs a new rotate node.
  15352. *
  15353. * @param {Node} positionNode - The position node.
  15354. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15355. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15356. */
  15357. constructor( positionNode, rotationNode ) {
  15358. super();
  15359. /**
  15360. * The position node.
  15361. *
  15362. * @type {Node}
  15363. */
  15364. this.positionNode = positionNode;
  15365. /**
  15366. * Represents the rotation that is applied to the position node.
  15367. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15368. *
  15369. * @type {Node}
  15370. */
  15371. this.rotationNode = rotationNode;
  15372. }
  15373. /**
  15374. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15375. *
  15376. * @param {NodeBuilder} builder - The current node builder.
  15377. * @return {String} The node's type.
  15378. */
  15379. getNodeType( builder ) {
  15380. return this.positionNode.getNodeType( builder );
  15381. }
  15382. setup( builder ) {
  15383. const { rotationNode, positionNode } = this;
  15384. const nodeType = this.getNodeType( builder );
  15385. if ( nodeType === 'vec2' ) {
  15386. const cosAngle = rotationNode.cos();
  15387. const sinAngle = rotationNode.sin();
  15388. const rotationMatrix = mat2(
  15389. cosAngle, sinAngle,
  15390. sinAngle.negate(), cosAngle
  15391. );
  15392. return rotationMatrix.mul( positionNode );
  15393. } else {
  15394. const rotation = rotationNode;
  15395. 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 ) );
  15396. 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 ) );
  15397. 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 ) );
  15398. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15399. }
  15400. }
  15401. }
  15402. /**
  15403. * TSL function for creating a rotate node.
  15404. *
  15405. * @function
  15406. * @param {Node} positionNode - The position node.
  15407. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15408. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15409. * @returns {RotateNode}
  15410. */
  15411. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15412. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15413. /**
  15414. * Node material version of `SpriteMaterial`.
  15415. *
  15416. * @augments NodeMaterial
  15417. */
  15418. class SpriteNodeMaterial extends NodeMaterial {
  15419. static get type() {
  15420. return 'SpriteNodeMaterial';
  15421. }
  15422. /**
  15423. * Constructs a new sprite node material.
  15424. *
  15425. * @param {Object?} parameters - The configuration parameter.
  15426. */
  15427. constructor( parameters ) {
  15428. super();
  15429. /**
  15430. * This flag can be used for type testing.
  15431. *
  15432. * @type {Boolean}
  15433. * @readonly
  15434. * @default true
  15435. */
  15436. this.isSpriteNodeMaterial = true;
  15437. this._useSizeAttenuation = true;
  15438. /**
  15439. * This property makes it possible to define the position of the sprite with a
  15440. * node. That can be useful when the material is used with instanced rendering
  15441. * and node data are defined with an instanced attribute node:
  15442. * ```js
  15443. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15444. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15445. * ```
  15446. * Another possibility is to compute the instanced data with a compute shader:
  15447. * ```js
  15448. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15449. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15450. * ```
  15451. *
  15452. * @type {Node<vec2>?}
  15453. * @default null
  15454. */
  15455. this.positionNode = null;
  15456. /**
  15457. * The rotation of sprite materials is by default inferred from the `rotation`,
  15458. * property. This node property allows to overwrite the default and define
  15459. * the rotation with a node instead.
  15460. *
  15461. * If you don't want to overwrite the rotation but modify the existing
  15462. * value instead, use {@link module:MaterialNode.materialRotation}.
  15463. *
  15464. * @type {Node<float>?}
  15465. * @default null
  15466. */
  15467. this.rotationNode = null;
  15468. /**
  15469. * This node property provides an additional way to scale sprites next to
  15470. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15471. * is multiplied with the scale value of this node in the vertex shader.
  15472. *
  15473. * @type {Node<vec2>?}
  15474. * @default null
  15475. */
  15476. this.scaleNode = null;
  15477. this.setDefaultValues( _defaultValues$2 );
  15478. this.setValues( parameters );
  15479. }
  15480. /**
  15481. * Setups the position node in view space. This method implements
  15482. * the sprite specific vertex shader.
  15483. *
  15484. * @param {NodeBuilder} builder - The current node builder.
  15485. * @return {Node<vec3>} The position in view space.
  15486. */
  15487. setupPositionView( builder ) {
  15488. const { object, camera } = builder;
  15489. const sizeAttenuation = this.sizeAttenuation;
  15490. const { positionNode, rotationNode, scaleNode } = this;
  15491. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15492. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15493. if ( scaleNode !== null ) {
  15494. scale = scale.mul( float( scaleNode ) );
  15495. }
  15496. if ( sizeAttenuation === false ) {
  15497. if ( camera.isPerspectiveCamera ) {
  15498. scale = scale.mul( mvPosition.z.negate() );
  15499. } else {
  15500. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15501. scale = scale.mul( orthoScale.mul( 2 ) );
  15502. }
  15503. }
  15504. let alignedPosition = positionGeometry.xy;
  15505. if ( object.center && object.center.isVector2 === true ) {
  15506. const center = reference$1( 'center', 'vec2', object );
  15507. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15508. }
  15509. alignedPosition = alignedPosition.mul( scale );
  15510. const rotation = float( rotationNode || materialRotation );
  15511. const rotatedPosition = rotate( alignedPosition, rotation );
  15512. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15513. }
  15514. copy( source ) {
  15515. this.positionNode = source.positionNode;
  15516. this.rotationNode = source.rotationNode;
  15517. this.scaleNode = source.scaleNode;
  15518. return super.copy( source );
  15519. }
  15520. /**
  15521. * Whether to use size attenuation or not.
  15522. *
  15523. * @type {Boolean}
  15524. * @default true
  15525. */
  15526. get sizeAttenuation() {
  15527. return this._useSizeAttenuation;
  15528. }
  15529. set sizeAttenuation( value ) {
  15530. if ( this._useSizeAttenuation !== value ) {
  15531. this._useSizeAttenuation = value;
  15532. this.needsUpdate = true;
  15533. }
  15534. }
  15535. }
  15536. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15537. /**
  15538. * Node material version of `PointsMaterial`.
  15539. *
  15540. * @augments NodeMaterial
  15541. */
  15542. class PointsNodeMaterial extends SpriteNodeMaterial {
  15543. static get type() {
  15544. return 'PointsNodeMaterial';
  15545. }
  15546. /**
  15547. * Constructs a new points node material.
  15548. *
  15549. * @param {Object?} parameters - The configuration parameter.
  15550. */
  15551. constructor( parameters ) {
  15552. super();
  15553. /**
  15554. * This node property provides an additional way to set the point size.
  15555. *
  15556. * @type {Node<vec2>?}
  15557. * @default null
  15558. */
  15559. this.sizeNode = null;
  15560. /**
  15561. * This flag can be used for type testing.
  15562. *
  15563. * @type {Boolean}
  15564. * @readonly
  15565. * @default true
  15566. */
  15567. this.isPointsNodeMaterial = true;
  15568. this.setDefaultValues( _defaultValues$1 );
  15569. this.setValues( parameters );
  15570. }
  15571. setupPositionView() {
  15572. const { positionNode } = this;
  15573. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15574. }
  15575. setupVertex( builder ) {
  15576. const mvp = super.setupVertex( builder );
  15577. // skip further processing if the material is not a node material
  15578. if ( builder.material.isNodeMaterial !== true ) {
  15579. return mvp;
  15580. }
  15581. // ndc space
  15582. const { rotationNode, scaleNode, sizeNode } = this;
  15583. const alignedPosition = positionGeometry.xy.toVar();
  15584. const aspect = viewport.z.div( viewport.w );
  15585. // rotation
  15586. if ( rotationNode && rotationNode.isNode ) {
  15587. const rotation = float( rotationNode );
  15588. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15589. }
  15590. // point size
  15591. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15592. if ( this.sizeAttenuation === true ) {
  15593. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15594. }
  15595. // scale
  15596. if ( scaleNode && scaleNode.isNode ) {
  15597. pointSize = pointSize.mul( vec2( scaleNode ) );
  15598. }
  15599. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15600. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15601. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15602. // back to clip space
  15603. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15604. //clipPos.xy += offset;
  15605. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15606. return mvp;
  15607. }
  15608. /**
  15609. * Whether alpha to coverage should be used or not.
  15610. *
  15611. * @type {Boolean}
  15612. * @default true
  15613. */
  15614. get alphaToCoverage() {
  15615. return this._useAlphaToCoverage;
  15616. }
  15617. set alphaToCoverage( value ) {
  15618. if ( this._useAlphaToCoverage !== value ) {
  15619. this._useAlphaToCoverage = value;
  15620. this.needsUpdate = true;
  15621. }
  15622. }
  15623. }
  15624. /**
  15625. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15626. *
  15627. * @augments LightingModel
  15628. */
  15629. class ShadowMaskModel extends LightingModel {
  15630. /**
  15631. * Constructs a new shadow mask model.
  15632. */
  15633. constructor() {
  15634. super();
  15635. /**
  15636. * The shadow mask node.
  15637. *
  15638. * @type {Node}
  15639. */
  15640. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15641. }
  15642. /**
  15643. * Only used to save the shadow mask.
  15644. *
  15645. * @param {Object} input - The input data.
  15646. */
  15647. direct( { shadowMask } ) {
  15648. this.shadowNode.mulAssign( shadowMask );
  15649. }
  15650. /**
  15651. * Uses the shadow mask to produce the final color.
  15652. *
  15653. * @param {ContextNode} context - The current node context.
  15654. */
  15655. finish( context ) {
  15656. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15657. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15658. }
  15659. }
  15660. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15661. /**
  15662. * Node material version of `ShadowMaterial`.
  15663. *
  15664. * @augments NodeMaterial
  15665. */
  15666. class ShadowNodeMaterial extends NodeMaterial {
  15667. static get type() {
  15668. return 'ShadowNodeMaterial';
  15669. }
  15670. /**
  15671. * Constructs a new shadow node material.
  15672. *
  15673. * @param {Object?} parameters - The configuration parameter.
  15674. */
  15675. constructor( parameters ) {
  15676. super();
  15677. /**
  15678. * This flag can be used for type testing.
  15679. *
  15680. * @type {Boolean}
  15681. * @readonly
  15682. * @default true
  15683. */
  15684. this.isShadowNodeMaterial = true;
  15685. /**
  15686. * Set to `true` because so it's possible to implement
  15687. * the shadow mask effect.
  15688. *
  15689. * @type {Boolean}
  15690. * @default true
  15691. */
  15692. this.lights = true;
  15693. this.setDefaultValues( _defaultValues );
  15694. this.setValues( parameters );
  15695. }
  15696. /**
  15697. * Setups the lighting model.
  15698. *
  15699. * @return {ShadowMaskModel} The lighting model.
  15700. */
  15701. setupLightingModel( /*builder*/ ) {
  15702. return new ShadowMaskModel();
  15703. }
  15704. }
  15705. /** @module Texture3DNode **/
  15706. const normal = Fn( ( { texture, uv } ) => {
  15707. const epsilon = 0.0001;
  15708. const ret = vec3().toVar();
  15709. If( uv.x.lessThan( epsilon ), () => {
  15710. ret.assign( vec3( 1, 0, 0 ) );
  15711. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15712. ret.assign( vec3( 0, 1, 0 ) );
  15713. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15714. ret.assign( vec3( 0, 0, 1 ) );
  15715. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15716. ret.assign( vec3( - 1, 0, 0 ) );
  15717. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15718. ret.assign( vec3( 0, - 1, 0 ) );
  15719. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15720. ret.assign( vec3( 0, 0, - 1 ) );
  15721. } ).Else( () => {
  15722. const step = 0.01;
  15723. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15724. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15725. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15726. ret.assign( vec3( x, y, z ) );
  15727. } );
  15728. return ret.normalize();
  15729. } );
  15730. /**
  15731. * This type of uniform node represents a 3D texture.
  15732. *
  15733. * @augments module:TextureNode~TextureNode
  15734. */
  15735. class Texture3DNode extends TextureNode {
  15736. static get type() {
  15737. return 'Texture3DNode';
  15738. }
  15739. /**
  15740. * Constructs a new 3D texture node.
  15741. *
  15742. * @param {Data3DTexture} value - The 3D texture.
  15743. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15744. * @param {Node<int>?} [levelNode=null] - The level node.
  15745. */
  15746. constructor( value, uvNode = null, levelNode = null ) {
  15747. super( value, uvNode, levelNode );
  15748. /**
  15749. * This flag can be used for type testing.
  15750. *
  15751. * @type {Boolean}
  15752. * @readonly
  15753. * @default true
  15754. */
  15755. this.isTexture3DNode = true;
  15756. }
  15757. /**
  15758. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15759. *
  15760. * @param {NodeBuilder} builder - The current node builder.
  15761. * @return {String} The input type.
  15762. */
  15763. getInputType( /*builder*/ ) {
  15764. return 'texture3D';
  15765. }
  15766. /**
  15767. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15768. * uv node.
  15769. *
  15770. * @return {Node<vec3>} The default uv node.
  15771. */
  15772. getDefaultUV() {
  15773. return vec3( 0.5, 0.5, 0.5 );
  15774. }
  15775. /**
  15776. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15777. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15778. *
  15779. * @param {Boolean} value - The update toggle.
  15780. */
  15781. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15782. /**
  15783. * Overwrites the default implementation to return the unmodified uv node.
  15784. *
  15785. * @param {NodeBuilder} builder - The current node builder.
  15786. * @param {Node} uvNode - The uv node to setup.
  15787. * @return {Node} The unmodified uv node.
  15788. */
  15789. setupUV( builder, uvNode ) {
  15790. const texture = this.value;
  15791. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15792. if ( this.sampler ) {
  15793. uvNode = uvNode.flipY();
  15794. } else {
  15795. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15796. }
  15797. }
  15798. return uvNode;
  15799. }
  15800. /**
  15801. * Generates the uv code snippet.
  15802. *
  15803. * @param {NodeBuilder} builder - The current node builder.
  15804. * @param {Node} uvNode - The uv node to generate code for.
  15805. * @return {String} The generated code snippet.
  15806. */
  15807. generateUV( builder, uvNode ) {
  15808. return uvNode.build( builder, 'vec3' );
  15809. }
  15810. /**
  15811. * TODO.
  15812. *
  15813. * @param {Node<vec3>} uvNode - The uv node .
  15814. * @return {Node<vec3>} TODO.
  15815. */
  15816. normal( uvNode ) {
  15817. return normal( { texture: this, uv: uvNode } );
  15818. }
  15819. }
  15820. /**
  15821. * TSL function for creating a 3D texture node.
  15822. *
  15823. * @function
  15824. * @param {Data3DTexture} value - The 3D texture.
  15825. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15826. * @param {Node<int>?} [levelNode=null] - The level node.
  15827. * @returns {Texture3DNode}
  15828. */
  15829. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15830. /** @module VolumeNodeMaterial **/
  15831. /**
  15832. * Node material intended for volume rendering. The volumetric data are
  15833. * defined with an instance of {@link Data3DTexture}.
  15834. *
  15835. * @augments NodeMaterial
  15836. */
  15837. class VolumeNodeMaterial extends NodeMaterial {
  15838. static get type() {
  15839. return 'VolumeNodeMaterial';
  15840. }
  15841. /**
  15842. * Constructs a new volume node material.
  15843. *
  15844. * @param {Object?} parameters - The configuration parameter.
  15845. */
  15846. constructor( parameters ) {
  15847. super();
  15848. /**
  15849. * This flag can be used for type testing.
  15850. *
  15851. * @type {Boolean}
  15852. * @readonly
  15853. * @default true
  15854. */
  15855. this.isVolumeNodeMaterial = true;
  15856. /**
  15857. * The base color of the volume.
  15858. *
  15859. * @type {Color}
  15860. * @default 100
  15861. */
  15862. this.base = new Color( 0xffffff );
  15863. /**
  15864. * A 3D data texture holding the volumetric data.
  15865. *
  15866. * @type {Data3DTexture?}
  15867. * @default null
  15868. */
  15869. this.map = null;
  15870. /**
  15871. * This number of samples for each ray that hits the mesh's surface
  15872. * and travels through the volume.
  15873. *
  15874. * @type {Number}
  15875. * @default 100
  15876. */
  15877. this.steps = 100;
  15878. /**
  15879. * Callback for {@link VolumeNodeMaterial#testNode}.
  15880. *
  15881. * @callback testNodeCallback
  15882. * @param {Data3DTexture<float>} map - The 3D texture.
  15883. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15884. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15885. * @param {Node<vec4>} finalColor - The final color.
  15886. */
  15887. /**
  15888. * The volume rendering of this material works by shooting rays
  15889. * from the camera position through each fragment of the mesh's
  15890. * surface and sample the inner volume in a raymarching fashion
  15891. * multiple times.
  15892. *
  15893. * This node can be used to assign a callback function of type `Fn`
  15894. * that will be executed per sample. The callback receives the
  15895. * texture, the sampled texture value as well as position on the surface
  15896. * where the rays enters the volume. The last parameter is a color
  15897. * that allows the callback to determine the final color.
  15898. *
  15899. * @type {testNodeCallback?}
  15900. * @default null
  15901. */
  15902. this.testNode = null;
  15903. this.setValues( parameters );
  15904. }
  15905. /**
  15906. * Setups the vertex and fragment stage of this node material.
  15907. *
  15908. * @param {NodeBuilder} builder - The current node builder.
  15909. */
  15910. setup( builder ) {
  15911. const map = texture3D( this.map, null, 0 );
  15912. const hitBox = Fn( ( { orig, dir } ) => {
  15913. const box_min = vec3( - 0.5 );
  15914. const box_max = vec3( 0.5 );
  15915. const inv_dir = dir.reciprocal();
  15916. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15917. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15918. const tmin = min$1( tmin_tmp, tmax_tmp );
  15919. const tmax = max$1( tmin_tmp, tmax_tmp );
  15920. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15921. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15922. return vec2( t0, t1 );
  15923. } );
  15924. this.fragmentNode = Fn( () => {
  15925. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15926. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15927. const rayDir = vDirection.normalize();
  15928. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15929. bounds.x.greaterThan( bounds.y ).discard();
  15930. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15931. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15932. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15933. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15934. delta.divAssign( materialReference( 'steps', 'float' ) );
  15935. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15936. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15937. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15938. if ( this.testNode !== null ) {
  15939. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15940. } else {
  15941. // default to show surface of mesh
  15942. ac.a.assign( 1 );
  15943. Break();
  15944. }
  15945. p.addAssign( rayDir.mul( delta ) );
  15946. } );
  15947. ac.a.equal( 0 ).discard();
  15948. return vec4( ac );
  15949. } )();
  15950. super.setup( builder );
  15951. }
  15952. }
  15953. /**
  15954. * This module manages the internal animation loop of the renderer.
  15955. *
  15956. * @private
  15957. */
  15958. class Animation {
  15959. /**
  15960. * Constructs a new animation loop management component.
  15961. *
  15962. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15963. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15964. */
  15965. constructor( nodes, info ) {
  15966. /**
  15967. * Renderer component for managing nodes related logic.
  15968. *
  15969. * @type {Nodes}
  15970. */
  15971. this.nodes = nodes;
  15972. /**
  15973. * Renderer component for managing metrics and monitoring data.
  15974. *
  15975. * @type {Info}
  15976. */
  15977. this.info = info;
  15978. /**
  15979. * A reference to the context from `requestAnimationFrame()` can
  15980. * be called (usually `window`).
  15981. *
  15982. * @type {Window|XRSession}
  15983. */
  15984. this._context = self;
  15985. /**
  15986. * The user-defined animation loop.
  15987. *
  15988. * @type {Function?}
  15989. * @default null
  15990. */
  15991. this._animationLoop = null;
  15992. /**
  15993. * The requestId which is returned from the `requestAnimationFrame()` call.
  15994. * Can be used to cancel the stop the animation loop.
  15995. *
  15996. * @type {Number?}
  15997. * @default null
  15998. */
  15999. this._requestId = null;
  16000. }
  16001. /**
  16002. * Starts the internal animation loop.
  16003. */
  16004. start() {
  16005. const update = ( time, frame ) => {
  16006. this._requestId = this._context.requestAnimationFrame( update );
  16007. if ( this.info.autoReset === true ) this.info.reset();
  16008. this.nodes.nodeFrame.update();
  16009. this.info.frame = this.nodes.nodeFrame.frameId;
  16010. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16011. };
  16012. update();
  16013. }
  16014. /**
  16015. * Stops the internal animation loop.
  16016. */
  16017. stop() {
  16018. this._context.cancelAnimationFrame( this._requestId );
  16019. this._requestId = null;
  16020. }
  16021. /**
  16022. * Returns the user-level animation loop.
  16023. *
  16024. * @return {Function} The animation loop.
  16025. */
  16026. getAnimationLoop() {
  16027. return this._animationLoop;
  16028. }
  16029. /**
  16030. * Defines the user-level animation loop.
  16031. *
  16032. * @param {Function} callback - The animation loop.
  16033. */
  16034. setAnimationLoop( callback ) {
  16035. this._animationLoop = callback;
  16036. }
  16037. /**
  16038. * Returns the animation context.
  16039. *
  16040. * @return {Window|XRSession} The animation context.
  16041. */
  16042. getContext() {
  16043. return this._context;
  16044. }
  16045. /**
  16046. * Defines the context in which `requestAnimationFrame()` is executed.
  16047. *
  16048. * @param {Window|XRSession} context - The context to set.
  16049. */
  16050. setContext( context ) {
  16051. this._context = context;
  16052. }
  16053. /**
  16054. * Frees all internal resources and stops the animation loop.
  16055. */
  16056. dispose() {
  16057. this.stop();
  16058. }
  16059. }
  16060. /**
  16061. * Data structure for the renderer. It allows defining values
  16062. * with chained, hierarchical keys. Keys are meant to be
  16063. * objects since the module internally works with Weak Maps
  16064. * for performance reasons.
  16065. *
  16066. * @private
  16067. */
  16068. class ChainMap {
  16069. /**
  16070. * Constructs a new Chain Map.
  16071. */
  16072. constructor() {
  16073. /**
  16074. * The root Weak Map.
  16075. *
  16076. * @type {WeakMap}
  16077. */
  16078. this.weakMap = new WeakMap();
  16079. }
  16080. /**
  16081. * Returns the value for the given array of keys.
  16082. *
  16083. * @param {Array<Object>} keys - List of keys.
  16084. * @return {Any} The value. Returns `undefined` if no value was found.
  16085. */
  16086. get( keys ) {
  16087. let map = this.weakMap;
  16088. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16089. map = map.get( keys[ i ] );
  16090. if ( map === undefined ) return undefined;
  16091. }
  16092. return map.get( keys[ keys.length - 1 ] );
  16093. }
  16094. /**
  16095. * Sets the value for the given keys.
  16096. *
  16097. * @param {Array<Object>} keys - List of keys.
  16098. * @param {Any} value - The value to set.
  16099. * @return {ChainMap} A reference to this Chain Map.
  16100. */
  16101. set( keys, value ) {
  16102. let map = this.weakMap;
  16103. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16104. const key = keys[ i ];
  16105. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16106. map = map.get( key );
  16107. }
  16108. map.set( keys[ keys.length - 1 ], value );
  16109. return this;
  16110. }
  16111. /**
  16112. * Deletes a value for the given keys.
  16113. *
  16114. * @param {Array<Object>} keys - The keys.
  16115. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16116. */
  16117. delete( keys ) {
  16118. let map = this.weakMap;
  16119. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16120. map = map.get( keys[ i ] );
  16121. if ( map === undefined ) return false;
  16122. }
  16123. return map.delete( keys[ keys.length - 1 ] );
  16124. }
  16125. }
  16126. let _id$9 = 0;
  16127. function getKeys( obj ) {
  16128. const keys = Object.keys( obj );
  16129. let proto = Object.getPrototypeOf( obj );
  16130. while ( proto ) {
  16131. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16132. for ( const key in descriptors ) {
  16133. if ( descriptors[ key ] !== undefined ) {
  16134. const descriptor = descriptors[ key ];
  16135. if ( descriptor && typeof descriptor.get === 'function' ) {
  16136. keys.push( key );
  16137. }
  16138. }
  16139. }
  16140. proto = Object.getPrototypeOf( proto );
  16141. }
  16142. return keys;
  16143. }
  16144. /**
  16145. * A render object is the renderer's representation of single entity that gets drawn
  16146. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16147. * scene since render objects also depend from the used material, the current render context
  16148. * and the current scene's lighting.
  16149. *
  16150. * In general, the basic process of the renderer is:
  16151. *
  16152. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16153. * - Process the render lists by calling one or more render commands for each render item.
  16154. * - For each render command, request a render object and perform the draw.
  16155. *
  16156. * The module provides an interface to get data required for the draw command like the actual
  16157. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16158. * creating render objects should only be done when necessary.
  16159. *
  16160. * @private
  16161. */
  16162. class RenderObject {
  16163. /**
  16164. * Constructs a new render object.
  16165. *
  16166. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16167. * @param {Geometries} geometries - Renderer component for managing geometries.
  16168. * @param {Renderer} renderer - The renderer.
  16169. * @param {Object3D} object - The 3D object.
  16170. * @param {Material} material - The 3D object's material.
  16171. * @param {Scene} scene - The scene the 3D object belongs to.
  16172. * @param {Camera} camera - The camera the object should be rendered with.
  16173. * @param {LightsNode} lightsNode - The lights node.
  16174. * @param {RenderContext} renderContext - The render context.
  16175. * @param {ClippingContext} clippingContext - The clipping context.
  16176. */
  16177. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16178. this.id = _id$9 ++;
  16179. /**
  16180. * Renderer component for managing nodes related logic.
  16181. *
  16182. * @type {Nodes}
  16183. * @private
  16184. */
  16185. this._nodes = nodes;
  16186. /**
  16187. * Renderer component for managing geometries.
  16188. *
  16189. * @type {Geometries}
  16190. * @private
  16191. */
  16192. this._geometries = geometries;
  16193. /**
  16194. * The renderer.
  16195. *
  16196. * @type {Renderer}
  16197. */
  16198. this.renderer = renderer;
  16199. /**
  16200. * The 3D object.
  16201. *
  16202. * @type {Object3D}
  16203. */
  16204. this.object = object;
  16205. /**
  16206. * The 3D object's material.
  16207. *
  16208. * @type {Material}
  16209. */
  16210. this.material = material;
  16211. /**
  16212. * The scene the 3D object belongs to.
  16213. *
  16214. * @type {Scene}
  16215. */
  16216. this.scene = scene;
  16217. /**
  16218. * The camera the 3D object should be rendered with.
  16219. *
  16220. * @type {Camera}
  16221. */
  16222. this.camera = camera;
  16223. /**
  16224. * The lights node.
  16225. *
  16226. * @type {LightsNode}
  16227. */
  16228. this.lightsNode = lightsNode;
  16229. /**
  16230. * The render context.
  16231. *
  16232. * @type {RenderContext}
  16233. */
  16234. this.context = renderContext;
  16235. /**
  16236. * The 3D object's geometry.
  16237. *
  16238. * @type {BufferGeometry}
  16239. */
  16240. this.geometry = object.geometry;
  16241. /**
  16242. * The render object's version.
  16243. *
  16244. * @type {Number}
  16245. */
  16246. this.version = material.version;
  16247. /**
  16248. * The draw range of the geometry.
  16249. *
  16250. * @type {Object?}
  16251. * @default null
  16252. */
  16253. this.drawRange = null;
  16254. /**
  16255. * An array holding the buffer attributes
  16256. * of the render object. This entails attribute
  16257. * definitions on geometry and node level.
  16258. *
  16259. * @type {Array<BufferAttribute>?}
  16260. * @default null
  16261. */
  16262. this.attributes = null;
  16263. /**
  16264. * A reference to a render pipeline the render
  16265. * object is processed with.
  16266. *
  16267. * @type {RenderPipeline}
  16268. * @default null
  16269. */
  16270. this.pipeline = null;
  16271. /**
  16272. * Only relevant for objects using
  16273. * multiple materials. This represents a group entry
  16274. * from the respective `BufferGeometry`.
  16275. *
  16276. * @type {{start: Number, count: Number}?}
  16277. * @default null
  16278. */
  16279. this.group = null;
  16280. /**
  16281. * An array holding the vertex buffers which can
  16282. * be buffer attributes but also interleaved buffers.
  16283. *
  16284. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16285. * @default null
  16286. */
  16287. this.vertexBuffers = null;
  16288. /**
  16289. * The parameters for the draw command.
  16290. *
  16291. * @type {Object?}
  16292. * @default null
  16293. */
  16294. this.drawParams = null;
  16295. /**
  16296. * If this render object is used inside a render bundle,
  16297. * this property points to the respective bundle group.
  16298. *
  16299. * @type {BundleGroup?}
  16300. * @default null
  16301. */
  16302. this.bundle = null;
  16303. /**
  16304. * The clipping context.
  16305. *
  16306. * @type {ClippingContext}
  16307. */
  16308. this.clippingContext = clippingContext;
  16309. /**
  16310. * The clipping context's cache key.
  16311. *
  16312. * @type {String}
  16313. */
  16314. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16315. /**
  16316. * The initial node cache key.
  16317. *
  16318. * @type {Number}
  16319. */
  16320. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16321. /**
  16322. * The initial cache key.
  16323. *
  16324. * @type {Number}
  16325. */
  16326. this.initialCacheKey = this.getCacheKey();
  16327. /**
  16328. * The node builder state.
  16329. *
  16330. * @type {NodeBuilderState?}
  16331. * @private
  16332. * @default null
  16333. */
  16334. this._nodeBuilderState = null;
  16335. /**
  16336. * An array of bindings.
  16337. *
  16338. * @type {Array<BindGroup>?}
  16339. * @private
  16340. * @default null
  16341. */
  16342. this._bindings = null;
  16343. /**
  16344. * Reference to the node material observer.
  16345. *
  16346. * @type {NodeMaterialObserver?}
  16347. * @private
  16348. * @default null
  16349. */
  16350. this._monitor = null;
  16351. /**
  16352. * An event listener which is defined by `RenderObjects`. It performs
  16353. * clean up tasks when `dispose()` on this render object.
  16354. *
  16355. * @method
  16356. */
  16357. this.onDispose = null;
  16358. /**
  16359. * This flag can be used for type testing.
  16360. *
  16361. * @type {Boolean}
  16362. * @readonly
  16363. * @default true
  16364. */
  16365. this.isRenderObject = true;
  16366. /**
  16367. * An event listener which is executed when `dispose()` is called on
  16368. * the render object's material.
  16369. *
  16370. * @method
  16371. */
  16372. this.onMaterialDispose = () => {
  16373. this.dispose();
  16374. };
  16375. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16376. }
  16377. /**
  16378. * Updates the clipping context.
  16379. *
  16380. * @param {ClippingContext} context - The clipping context to set.
  16381. */
  16382. updateClipping( context ) {
  16383. this.clippingContext = context;
  16384. }
  16385. /**
  16386. * Whether the clipping requires an update or not.
  16387. *
  16388. * @type {Boolean}
  16389. * @readonly
  16390. */
  16391. get clippingNeedsUpdate() {
  16392. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16393. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16394. return true;
  16395. }
  16396. /**
  16397. * The number of clipping planes defined in context of hardware clipping.
  16398. *
  16399. * @type {Number}
  16400. * @readonly
  16401. */
  16402. get hardwareClippingPlanes() {
  16403. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16404. }
  16405. /**
  16406. * Returns the node builder state of this render object.
  16407. *
  16408. * @return {NodeBuilderState} The node builder state.
  16409. */
  16410. getNodeBuilderState() {
  16411. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16412. }
  16413. /**
  16414. * Returns the node material observer of this render object.
  16415. *
  16416. * @return {NodeMaterialObserver} The node material observer.
  16417. */
  16418. getMonitor() {
  16419. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16420. }
  16421. /**
  16422. * Returns an array of bind groups of this render object.
  16423. *
  16424. * @return {Array<BindGroup>} The bindings.
  16425. */
  16426. getBindings() {
  16427. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16428. }
  16429. /**
  16430. * Returns a binding group by group name of this render object.
  16431. *
  16432. * @param {String} name - The name of the binding group.
  16433. * @return {BindGroup?} The bindings.
  16434. */
  16435. getBindingGroup( name ) {
  16436. for ( const bindingGroup of this.getBindings() ) {
  16437. if ( bindingGroup.name === name ) {
  16438. return bindingGroup;
  16439. }
  16440. }
  16441. }
  16442. /**
  16443. * Returns the index of the render object's geometry.
  16444. *
  16445. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16446. */
  16447. getIndex() {
  16448. return this._geometries.getIndex( this );
  16449. }
  16450. /**
  16451. * Returns the indirect buffer attribute.
  16452. *
  16453. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16454. */
  16455. getIndirect() {
  16456. return this._geometries.getIndirect( this );
  16457. }
  16458. /**
  16459. * Returns an array that acts as a key for identifying the render object in a chain map.
  16460. *
  16461. * @return {Array<Object>} An array with object references.
  16462. */
  16463. getChainArray() {
  16464. return [ this.object, this.material, this.context, this.lightsNode ];
  16465. }
  16466. /**
  16467. * This method is used when the geometry of a 3D object has been exchanged and the
  16468. * respective render object now requires an update.
  16469. *
  16470. * @param {BufferGeometry} geometry - The geometry to set.
  16471. */
  16472. setGeometry( geometry ) {
  16473. this.geometry = geometry;
  16474. this.attributes = null;
  16475. }
  16476. /**
  16477. * Returns the buffer attributes of the render object. The returned array holds
  16478. * attribute definitions on geometry and node level.
  16479. *
  16480. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16481. */
  16482. getAttributes() {
  16483. if ( this.attributes !== null ) return this.attributes;
  16484. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16485. const geometry = this.geometry;
  16486. const attributes = [];
  16487. const vertexBuffers = new Set();
  16488. for ( const nodeAttribute of nodeAttributes ) {
  16489. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16490. if ( attribute === undefined ) continue;
  16491. attributes.push( attribute );
  16492. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16493. vertexBuffers.add( bufferAttribute );
  16494. }
  16495. this.attributes = attributes;
  16496. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16497. return attributes;
  16498. }
  16499. /**
  16500. * Returns the vertex buffers of the render object.
  16501. *
  16502. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16503. */
  16504. getVertexBuffers() {
  16505. if ( this.vertexBuffers === null ) this.getAttributes();
  16506. return this.vertexBuffers;
  16507. }
  16508. /**
  16509. * Returns the draw parameters for the render object.
  16510. *
  16511. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16512. */
  16513. getDrawParameters() {
  16514. const { object, material, geometry, group, drawRange } = this;
  16515. const drawParams = this.drawParams || ( this.drawParams = {
  16516. vertexCount: 0,
  16517. firstVertex: 0,
  16518. instanceCount: 0,
  16519. firstInstance: 0
  16520. } );
  16521. const index = this.getIndex();
  16522. const hasIndex = ( index !== null );
  16523. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16524. if ( instanceCount === 0 ) return null;
  16525. drawParams.instanceCount = instanceCount;
  16526. if ( object.isBatchedMesh === true ) return drawParams;
  16527. let rangeFactor = 1;
  16528. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16529. rangeFactor = 2;
  16530. }
  16531. let firstVertex = drawRange.start * rangeFactor;
  16532. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16533. if ( group !== null ) {
  16534. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16535. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16536. }
  16537. const position = geometry.attributes.position;
  16538. let itemCount = Infinity;
  16539. if ( hasIndex ) {
  16540. itemCount = index.count;
  16541. } else if ( position !== undefined && position !== null ) {
  16542. itemCount = position.count;
  16543. }
  16544. firstVertex = Math.max( firstVertex, 0 );
  16545. lastVertex = Math.min( lastVertex, itemCount );
  16546. const count = lastVertex - firstVertex;
  16547. if ( count < 0 || count === Infinity ) return null;
  16548. drawParams.vertexCount = count;
  16549. drawParams.firstVertex = firstVertex;
  16550. return drawParams;
  16551. }
  16552. /**
  16553. * Returns the render object's geometry cache key.
  16554. *
  16555. * The geometry cache key is part of the material cache key.
  16556. *
  16557. * @return {String} The geometry cache key.
  16558. */
  16559. getGeometryCacheKey() {
  16560. const { geometry } = this;
  16561. let cacheKey = '';
  16562. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16563. const attribute = geometry.attributes[ name ];
  16564. cacheKey += name + ',';
  16565. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16566. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16567. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16568. if ( attribute.normalized ) cacheKey += 'n,';
  16569. }
  16570. // structural equality isn't sufficient for morph targets since the
  16571. // data are maintained in textures. only if the targets are all equal
  16572. // the texture and thus the instance of `MorphNode` can be shared.
  16573. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16574. const targets = geometry.morphAttributes[ name ];
  16575. cacheKey += 'morph-' + name + ',';
  16576. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16577. const attribute = targets[ i ];
  16578. cacheKey += attribute.id + ',';
  16579. }
  16580. }
  16581. if ( geometry.index ) {
  16582. cacheKey += 'index,';
  16583. }
  16584. return cacheKey;
  16585. }
  16586. /**
  16587. * Returns the render object's material cache key.
  16588. *
  16589. * The material cache key is part of the render object cache key.
  16590. *
  16591. * @return {Number} The material cache key.
  16592. */
  16593. getMaterialCacheKey() {
  16594. const { object, material } = this;
  16595. let cacheKey = material.customProgramCacheKey();
  16596. for ( const property of getKeys( material ) ) {
  16597. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16598. const value = material[ property ];
  16599. let valueKey;
  16600. if ( value !== null ) {
  16601. // some material values require a formatting
  16602. const type = typeof value;
  16603. if ( type === 'number' ) {
  16604. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16605. } else if ( type === 'object' ) {
  16606. valueKey = '{';
  16607. if ( value.isTexture ) {
  16608. valueKey += value.mapping;
  16609. }
  16610. valueKey += '}';
  16611. } else {
  16612. valueKey = String( value );
  16613. }
  16614. } else {
  16615. valueKey = String( value );
  16616. }
  16617. cacheKey += /*property + ':' +*/ valueKey + ',';
  16618. }
  16619. cacheKey += this.clippingContextCacheKey + ',';
  16620. if ( object.geometry ) {
  16621. cacheKey += this.getGeometryCacheKey();
  16622. }
  16623. if ( object.skeleton ) {
  16624. cacheKey += object.skeleton.bones.length + ',';
  16625. }
  16626. if ( object.isBatchedMesh ) {
  16627. cacheKey += object._matricesTexture.uuid + ',';
  16628. if ( object._colorsTexture !== null ) {
  16629. cacheKey += object._colorsTexture.uuid + ',';
  16630. }
  16631. }
  16632. if ( object.count > 1 ) {
  16633. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16634. cacheKey += object.uuid + ',';
  16635. }
  16636. cacheKey += object.receiveShadow + ',';
  16637. return hashString( cacheKey );
  16638. }
  16639. /**
  16640. * Whether the geometry requires an update or not.
  16641. *
  16642. * @type {Boolean}
  16643. * @readonly
  16644. */
  16645. get needsGeometryUpdate() {
  16646. return this.geometry.id !== this.object.geometry.id;
  16647. }
  16648. /**
  16649. * Whether the render object requires an update or not.
  16650. *
  16651. * Note: There are two distinct places where render objects are checked for an update.
  16652. *
  16653. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16654. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16655. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16656. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16657. * a need for a refresh due to material, geometry or object related value changes.
  16658. *
  16659. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16660. * that performs the 'needsUpdate' check.
  16661. *
  16662. * @type {Boolean}
  16663. * @readonly
  16664. */
  16665. get needsUpdate() {
  16666. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16667. }
  16668. /**
  16669. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16670. *
  16671. * @return {Number} The cache key.
  16672. */
  16673. getDynamicCacheKey() {
  16674. let cacheKey = 0;
  16675. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16676. // the renderer is inside a shadow pass.
  16677. if ( this.material.isShadowPassMaterial !== true ) {
  16678. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16679. }
  16680. if ( this.camera.isArrayCamera ) {
  16681. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  16682. }
  16683. if ( this.object.receiveShadow ) {
  16684. cacheKey = hash$1( cacheKey, 1 );
  16685. }
  16686. return cacheKey;
  16687. }
  16688. /**
  16689. * Returns the render object's cache key.
  16690. *
  16691. * @return {Number} The cache key.
  16692. */
  16693. getCacheKey() {
  16694. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16695. }
  16696. /**
  16697. * Frees internal resources.
  16698. */
  16699. dispose() {
  16700. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16701. this.onDispose();
  16702. }
  16703. }
  16704. const _chainKeys$5 = [];
  16705. /**
  16706. * This module manages the render objects of the renderer.
  16707. *
  16708. * @private
  16709. */
  16710. class RenderObjects {
  16711. /**
  16712. * Constructs a new render object management component.
  16713. *
  16714. * @param {Renderer} renderer - The renderer.
  16715. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16716. * @param {Geometries} geometries - Renderer component for managing geometries.
  16717. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16718. * @param {Bindings} bindings - Renderer component for managing bindings.
  16719. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16720. */
  16721. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16722. /**
  16723. * The renderer.
  16724. *
  16725. * @type {Renderer}
  16726. */
  16727. this.renderer = renderer;
  16728. /**
  16729. * Renderer component for managing nodes related logic.
  16730. *
  16731. * @type {Nodes}
  16732. */
  16733. this.nodes = nodes;
  16734. /**
  16735. * Renderer component for managing geometries.
  16736. *
  16737. * @type {Geometries}
  16738. */
  16739. this.geometries = geometries;
  16740. /**
  16741. * Renderer component for managing pipelines.
  16742. *
  16743. * @type {Pipelines}
  16744. */
  16745. this.pipelines = pipelines;
  16746. /**
  16747. * Renderer component for managing bindings.
  16748. *
  16749. * @type {Bindings}
  16750. */
  16751. this.bindings = bindings;
  16752. /**
  16753. * Renderer component for managing metrics and monitoring data.
  16754. *
  16755. * @type {Info}
  16756. */
  16757. this.info = info;
  16758. /**
  16759. * A dictionary that manages render contexts in chain maps
  16760. * for each pass ID.
  16761. *
  16762. * @type {Object<String,ChainMap>}
  16763. */
  16764. this.chainMaps = {};
  16765. }
  16766. /**
  16767. * Returns a render object for the given object and state data.
  16768. *
  16769. * @param {Object3D} object - The 3D object.
  16770. * @param {Material} material - The 3D object's material.
  16771. * @param {Scene} scene - The scene the 3D object belongs to.
  16772. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16773. * @param {LightsNode} lightsNode - The lights node.
  16774. * @param {RenderContext} renderContext - The render context.
  16775. * @param {ClippingContext} clippingContext - The clipping context.
  16776. * @param {String?} passId - An optional ID for identifying the pass.
  16777. * @return {RenderObject} The render object.
  16778. */
  16779. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16780. const chainMap = this.getChainMap( passId );
  16781. // reuse chainArray
  16782. _chainKeys$5[ 0 ] = object;
  16783. _chainKeys$5[ 1 ] = material;
  16784. _chainKeys$5[ 2 ] = renderContext;
  16785. _chainKeys$5[ 3 ] = lightsNode;
  16786. let renderObject = chainMap.get( _chainKeys$5 );
  16787. if ( renderObject === undefined ) {
  16788. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16789. chainMap.set( _chainKeys$5, renderObject );
  16790. } else {
  16791. renderObject.updateClipping( clippingContext );
  16792. if ( renderObject.needsGeometryUpdate ) {
  16793. renderObject.setGeometry( object.geometry );
  16794. }
  16795. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16796. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16797. renderObject.dispose();
  16798. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16799. } else {
  16800. renderObject.version = material.version;
  16801. }
  16802. }
  16803. }
  16804. _chainKeys$5.length = 0;
  16805. return renderObject;
  16806. }
  16807. /**
  16808. * Returns a chain map for the given pass ID.
  16809. *
  16810. * @param {String} [passId='default'] - The pass ID.
  16811. * @return {ChainMap} The chain map.
  16812. */
  16813. getChainMap( passId = 'default' ) {
  16814. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16815. }
  16816. /**
  16817. * Frees internal resources.
  16818. */
  16819. dispose() {
  16820. this.chainMaps = {};
  16821. }
  16822. /**
  16823. * Factory method for creating render objects with the given list of parameters.
  16824. *
  16825. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16826. * @param {Geometries} geometries - Renderer component for managing geometries.
  16827. * @param {Renderer} renderer - The renderer.
  16828. * @param {Object3D} object - The 3D object.
  16829. * @param {Material} material - The object's material.
  16830. * @param {Scene} scene - The scene the 3D object belongs to.
  16831. * @param {Camera} camera - The camera the object should be rendered with.
  16832. * @param {LightsNode} lightsNode - The lights node.
  16833. * @param {RenderContext} renderContext - The render context.
  16834. * @param {ClippingContext} clippingContext - The clipping context.
  16835. * @param {String?} passId - An optional ID for identifying the pass.
  16836. * @return {RenderObject} The render object.
  16837. */
  16838. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16839. const chainMap = this.getChainMap( passId );
  16840. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16841. renderObject.onDispose = () => {
  16842. this.pipelines.delete( renderObject );
  16843. this.bindings.delete( renderObject );
  16844. this.nodes.delete( renderObject );
  16845. chainMap.delete( renderObject.getChainArray() );
  16846. };
  16847. return renderObject;
  16848. }
  16849. }
  16850. /**
  16851. * Data structure for the renderer. It is intended to manage
  16852. * data of objects in dictionaries.
  16853. *
  16854. * @private
  16855. */
  16856. class DataMap {
  16857. /**
  16858. * Constructs a new data map.
  16859. */
  16860. constructor() {
  16861. /**
  16862. * `DataMap` internally uses a weak map
  16863. * to manage its data.
  16864. *
  16865. * @type {WeakMap}
  16866. */
  16867. this.data = new WeakMap();
  16868. }
  16869. /**
  16870. * Returns the dictionary for the given object.
  16871. *
  16872. * @param {Object} object - The object.
  16873. * @return {Object} The dictionary.
  16874. */
  16875. get( object ) {
  16876. let map = this.data.get( object );
  16877. if ( map === undefined ) {
  16878. map = {};
  16879. this.data.set( object, map );
  16880. }
  16881. return map;
  16882. }
  16883. /**
  16884. * Deletes the dictionary for the given object.
  16885. *
  16886. * @param {Object} object - The object.
  16887. * @return {Object?} The deleted dictionary.
  16888. */
  16889. delete( object ) {
  16890. let map = null;
  16891. if ( this.data.has( object ) ) {
  16892. map = this.data.get( object );
  16893. this.data.delete( object );
  16894. }
  16895. return map;
  16896. }
  16897. /**
  16898. * Returns `true` if the given object has a dictionary defined.
  16899. *
  16900. * @param {Object} object - The object to test.
  16901. * @return {Boolean} Whether a dictionary is defined or not.
  16902. */
  16903. has( object ) {
  16904. return this.data.has( object );
  16905. }
  16906. /**
  16907. * Frees internal resources.
  16908. */
  16909. dispose() {
  16910. this.data = new WeakMap();
  16911. }
  16912. }
  16913. const AttributeType = {
  16914. VERTEX: 1,
  16915. INDEX: 2,
  16916. STORAGE: 3,
  16917. INDIRECT: 4
  16918. };
  16919. // size of a chunk in bytes (STD140 layout)
  16920. const GPU_CHUNK_BYTES = 16;
  16921. // @TODO: Move to src/constants.js
  16922. const BlendColorFactor = 211;
  16923. const OneMinusBlendColorFactor = 212;
  16924. /**
  16925. * This renderer module manages geometry attributes.
  16926. *
  16927. * @private
  16928. * @augments DataMap
  16929. */
  16930. class Attributes extends DataMap {
  16931. /**
  16932. * Constructs a new attribute management component.
  16933. *
  16934. * @param {Backend} backend - The renderer's backend.
  16935. */
  16936. constructor( backend ) {
  16937. super();
  16938. /**
  16939. * The renderer's backend.
  16940. *
  16941. * @type {Backend}
  16942. */
  16943. this.backend = backend;
  16944. }
  16945. /**
  16946. * Deletes the data for the given attribute.
  16947. *
  16948. * @param {BufferAttribute} attribute - The attribute.
  16949. * @return {Object} The deleted attribute data.
  16950. */
  16951. delete( attribute ) {
  16952. const attributeData = super.delete( attribute );
  16953. if ( attributeData !== undefined ) {
  16954. this.backend.destroyAttribute( attribute );
  16955. }
  16956. return attributeData;
  16957. }
  16958. /**
  16959. * Updates the given attribute. This method creates attribute buffers
  16960. * for new attributes and updates data for existing ones.
  16961. *
  16962. * @param {BufferAttribute} attribute - The attribute to update.
  16963. * @param {Number} type - The attribute type.
  16964. */
  16965. update( attribute, type ) {
  16966. const data = this.get( attribute );
  16967. if ( data.version === undefined ) {
  16968. if ( type === AttributeType.VERTEX ) {
  16969. this.backend.createAttribute( attribute );
  16970. } else if ( type === AttributeType.INDEX ) {
  16971. this.backend.createIndexAttribute( attribute );
  16972. } else if ( type === AttributeType.STORAGE ) {
  16973. this.backend.createStorageAttribute( attribute );
  16974. } else if ( type === AttributeType.INDIRECT ) {
  16975. this.backend.createIndirectStorageAttribute( attribute );
  16976. }
  16977. data.version = this._getBufferAttribute( attribute ).version;
  16978. } else {
  16979. const bufferAttribute = this._getBufferAttribute( attribute );
  16980. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16981. this.backend.updateAttribute( attribute );
  16982. data.version = bufferAttribute.version;
  16983. }
  16984. }
  16985. }
  16986. /**
  16987. * Utility method for handling interleaved buffer attributes correctly.
  16988. * To process them, their `InterleavedBuffer` is returned.
  16989. *
  16990. * @param {BufferAttribute} attribute - The attribute.
  16991. * @return {BufferAttribute|InterleavedBuffer}
  16992. */
  16993. _getBufferAttribute( attribute ) {
  16994. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16995. return attribute;
  16996. }
  16997. }
  16998. /**
  16999. * Returns `true` if the given array has values that require an Uint32 array type.
  17000. *
  17001. * @private
  17002. * @function
  17003. * @param {Array<Number>} array - The array to test.
  17004. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  17005. */
  17006. function arrayNeedsUint32( array ) {
  17007. // assumes larger values usually on last
  17008. for ( let i = array.length - 1; i >= 0; -- i ) {
  17009. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  17010. }
  17011. return false;
  17012. }
  17013. /**
  17014. * Returns the wireframe version for the given geometry.
  17015. *
  17016. * @private
  17017. * @function
  17018. * @param {BufferGeometry} geometry - The geometry.
  17019. * @return {Number} The version.
  17020. */
  17021. function getWireframeVersion( geometry ) {
  17022. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17023. }
  17024. /**
  17025. * Returns a wireframe index attribute for the given geometry.
  17026. *
  17027. * @private
  17028. * @function
  17029. * @param {BufferGeometry} geometry - The geometry.
  17030. * @return {BufferAttribute} The wireframe index attribute.
  17031. */
  17032. function getWireframeIndex( geometry ) {
  17033. const indices = [];
  17034. const geometryIndex = geometry.index;
  17035. const geometryPosition = geometry.attributes.position;
  17036. if ( geometryIndex !== null ) {
  17037. const array = geometryIndex.array;
  17038. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17039. const a = array[ i + 0 ];
  17040. const b = array[ i + 1 ];
  17041. const c = array[ i + 2 ];
  17042. indices.push( a, b, b, c, c, a );
  17043. }
  17044. } else {
  17045. const array = geometryPosition.array;
  17046. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17047. const a = i + 0;
  17048. const b = i + 1;
  17049. const c = i + 2;
  17050. indices.push( a, b, b, c, c, a );
  17051. }
  17052. }
  17053. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17054. attribute.version = getWireframeVersion( geometry );
  17055. return attribute;
  17056. }
  17057. /**
  17058. * This renderer module manages geometries.
  17059. *
  17060. * @private
  17061. * @augments DataMap
  17062. */
  17063. class Geometries extends DataMap {
  17064. /**
  17065. * Constructs a new geometry management component.
  17066. *
  17067. * @param {Attributes} attributes - Renderer component for managing attributes.
  17068. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17069. */
  17070. constructor( attributes, info ) {
  17071. super();
  17072. /**
  17073. * Renderer component for managing attributes.
  17074. *
  17075. * @type {Attributes}
  17076. */
  17077. this.attributes = attributes;
  17078. /**
  17079. * Renderer component for managing metrics and monitoring data.
  17080. *
  17081. * @type {Info}
  17082. */
  17083. this.info = info;
  17084. /**
  17085. * Weak Map for managing attributes for wireframe rendering.
  17086. *
  17087. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17088. */
  17089. this.wireframes = new WeakMap();
  17090. /**
  17091. * This Weak Map is used to make sure buffer attributes are
  17092. * updated only once per render call.
  17093. *
  17094. * @type {WeakMap<BufferAttribute,Number>}
  17095. */
  17096. this.attributeCall = new WeakMap();
  17097. }
  17098. /**
  17099. * Returns `true` if the given render object has an initialized geometry.
  17100. *
  17101. * @param {RenderObject} renderObject - The render object.
  17102. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17103. */
  17104. has( renderObject ) {
  17105. const geometry = renderObject.geometry;
  17106. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17107. }
  17108. /**
  17109. * Prepares the geometry of the given render object for rendering.
  17110. *
  17111. * @param {RenderObject} renderObject - The render object.
  17112. */
  17113. updateForRender( renderObject ) {
  17114. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17115. this.updateAttributes( renderObject );
  17116. }
  17117. /**
  17118. * Initializes the geometry of the given render object.
  17119. *
  17120. * @param {RenderObject} renderObject - The render object.
  17121. */
  17122. initGeometry( renderObject ) {
  17123. const geometry = renderObject.geometry;
  17124. const geometryData = this.get( geometry );
  17125. geometryData.initialized = true;
  17126. this.info.memory.geometries ++;
  17127. const onDispose = () => {
  17128. this.info.memory.geometries --;
  17129. const index = geometry.index;
  17130. const geometryAttributes = renderObject.getAttributes();
  17131. if ( index !== null ) {
  17132. this.attributes.delete( index );
  17133. }
  17134. for ( const geometryAttribute of geometryAttributes ) {
  17135. this.attributes.delete( geometryAttribute );
  17136. }
  17137. const wireframeAttribute = this.wireframes.get( geometry );
  17138. if ( wireframeAttribute !== undefined ) {
  17139. this.attributes.delete( wireframeAttribute );
  17140. }
  17141. geometry.removeEventListener( 'dispose', onDispose );
  17142. };
  17143. geometry.addEventListener( 'dispose', onDispose );
  17144. }
  17145. /**
  17146. * Updates the geometry attributes of the given render object.
  17147. *
  17148. * @param {RenderObject} renderObject - The render object.
  17149. */
  17150. updateAttributes( renderObject ) {
  17151. // attributes
  17152. const attributes = renderObject.getAttributes();
  17153. for ( const attribute of attributes ) {
  17154. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17155. this.updateAttribute( attribute, AttributeType.STORAGE );
  17156. } else {
  17157. this.updateAttribute( attribute, AttributeType.VERTEX );
  17158. }
  17159. }
  17160. // indexes
  17161. const index = this.getIndex( renderObject );
  17162. if ( index !== null ) {
  17163. this.updateAttribute( index, AttributeType.INDEX );
  17164. }
  17165. // indirect
  17166. const indirect = renderObject.geometry.indirect;
  17167. if ( indirect !== null ) {
  17168. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17169. }
  17170. }
  17171. /**
  17172. * Updates the given attribute.
  17173. *
  17174. * @param {BufferAttribute} attribute - The attribute to update.
  17175. * @param {Number} type - The attribute type.
  17176. */
  17177. updateAttribute( attribute, type ) {
  17178. const callId = this.info.render.calls;
  17179. if ( ! attribute.isInterleavedBufferAttribute ) {
  17180. if ( this.attributeCall.get( attribute ) !== callId ) {
  17181. this.attributes.update( attribute, type );
  17182. this.attributeCall.set( attribute, callId );
  17183. }
  17184. } else {
  17185. if ( this.attributeCall.get( attribute ) === undefined ) {
  17186. this.attributes.update( attribute, type );
  17187. this.attributeCall.set( attribute, callId );
  17188. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17189. this.attributes.update( attribute, type );
  17190. this.attributeCall.set( attribute.data, callId );
  17191. this.attributeCall.set( attribute, callId );
  17192. }
  17193. }
  17194. }
  17195. /**
  17196. * Returns the indirect buffer attribute of the given render object.
  17197. *
  17198. * @param {RenderObject} renderObject - The render object.
  17199. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17200. */
  17201. getIndirect( renderObject ) {
  17202. return renderObject.geometry.indirect;
  17203. }
  17204. /**
  17205. * Returns the index of the given render object's geometry. This is implemented
  17206. * in a method to return a wireframe index if necessary.
  17207. *
  17208. * @param {RenderObject} renderObject - The render object.
  17209. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17210. */
  17211. getIndex( renderObject ) {
  17212. const { geometry, material } = renderObject;
  17213. let index = geometry.index;
  17214. if ( material.wireframe === true ) {
  17215. const wireframes = this.wireframes;
  17216. let wireframeAttribute = wireframes.get( geometry );
  17217. if ( wireframeAttribute === undefined ) {
  17218. wireframeAttribute = getWireframeIndex( geometry );
  17219. wireframes.set( geometry, wireframeAttribute );
  17220. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17221. this.attributes.delete( wireframeAttribute );
  17222. wireframeAttribute = getWireframeIndex( geometry );
  17223. wireframes.set( geometry, wireframeAttribute );
  17224. }
  17225. index = wireframeAttribute;
  17226. }
  17227. return index;
  17228. }
  17229. }
  17230. /**
  17231. * This renderer module provides a series of statistical information
  17232. * about the GPU memory and the rendering process. Useful for debugging
  17233. * and monitoring.
  17234. */
  17235. class Info {
  17236. /**
  17237. * Constructs a new info component.
  17238. */
  17239. constructor() {
  17240. /**
  17241. * Whether frame related metrics should automatically
  17242. * be resetted or not. This property should be set to `false`
  17243. * by apps which manage their own animation loop. They must
  17244. * then call `renderer.info.reset()` once per frame manually.
  17245. *
  17246. * @type {Boolean}
  17247. * @default true
  17248. */
  17249. this.autoReset = true;
  17250. /**
  17251. * The current frame ID. This ID is managed
  17252. * by `NodeFrame`.
  17253. *
  17254. * @type {Number}
  17255. * @readonly
  17256. * @default 0
  17257. */
  17258. this.frame = 0;
  17259. /**
  17260. * The number of render calls since the
  17261. * app has been started.
  17262. *
  17263. * @type {Number}
  17264. * @readonly
  17265. * @default 0
  17266. */
  17267. this.calls = 0;
  17268. /**
  17269. * Render related metrics.
  17270. *
  17271. * @type {Object}
  17272. * @readonly
  17273. * @property {Number} calls - The number of render calls since the app has been started.
  17274. * @property {Number} frameCalls - The number of render calls of the current frame.
  17275. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17276. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17277. * @property {Number} points - The number of rendered point primitives of the current frame.
  17278. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17279. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17280. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17281. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17282. */
  17283. this.render = {
  17284. calls: 0,
  17285. frameCalls: 0,
  17286. drawCalls: 0,
  17287. triangles: 0,
  17288. points: 0,
  17289. lines: 0,
  17290. timestamp: 0,
  17291. previousFrameCalls: 0,
  17292. timestampCalls: 0
  17293. };
  17294. /**
  17295. * Compute related metrics.
  17296. *
  17297. * @type {Object}
  17298. * @readonly
  17299. * @property {Number} calls - The number of compute calls since the app has been started.
  17300. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17301. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17302. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17303. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17304. */
  17305. this.compute = {
  17306. calls: 0,
  17307. frameCalls: 0,
  17308. timestamp: 0,
  17309. previousFrameCalls: 0,
  17310. timestampCalls: 0
  17311. };
  17312. /**
  17313. * Memory related metrics.
  17314. *
  17315. * @type {Object}
  17316. * @readonly
  17317. * @property {Number} geometries - The number of active geometries.
  17318. * @property {Number} frameCalls - The number of active textures.
  17319. */
  17320. this.memory = {
  17321. geometries: 0,
  17322. textures: 0
  17323. };
  17324. }
  17325. /**
  17326. * This method should be executed per draw call and updates the corresponding metrics.
  17327. *
  17328. * @param {Object3D} object - The 3D object that is going to be rendered.
  17329. * @param {Number} count - The vertex or index count.
  17330. * @param {Number} instanceCount - The instance count.
  17331. */
  17332. update( object, count, instanceCount ) {
  17333. this.render.drawCalls ++;
  17334. if ( object.isMesh || object.isSprite ) {
  17335. this.render.triangles += instanceCount * ( count / 3 );
  17336. } else if ( object.isPoints ) {
  17337. this.render.points += instanceCount * count;
  17338. } else if ( object.isLineSegments ) {
  17339. this.render.lines += instanceCount * ( count / 2 );
  17340. } else if ( object.isLine ) {
  17341. this.render.lines += instanceCount * ( count - 1 );
  17342. } else {
  17343. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17344. }
  17345. }
  17346. /**
  17347. * Used by async render methods to updated timestamp metrics.
  17348. *
  17349. * @param {('render'|'compute')} type - The type of render call.
  17350. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17351. */
  17352. updateTimestamp( type, time ) {
  17353. if ( this[ type ].timestampCalls === 0 ) {
  17354. this[ type ].timestamp = 0;
  17355. }
  17356. this[ type ].timestamp += time;
  17357. this[ type ].timestampCalls ++;
  17358. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17359. this[ type ].timestampCalls = 0;
  17360. }
  17361. }
  17362. /**
  17363. * Resets frame related metrics.
  17364. */
  17365. reset() {
  17366. const previousRenderFrameCalls = this.render.frameCalls;
  17367. this.render.previousFrameCalls = previousRenderFrameCalls;
  17368. const previousComputeFrameCalls = this.compute.frameCalls;
  17369. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17370. this.render.drawCalls = 0;
  17371. this.render.frameCalls = 0;
  17372. this.compute.frameCalls = 0;
  17373. this.render.triangles = 0;
  17374. this.render.points = 0;
  17375. this.render.lines = 0;
  17376. }
  17377. /**
  17378. * Performs a complete reset of the object.
  17379. */
  17380. dispose() {
  17381. this.reset();
  17382. this.calls = 0;
  17383. this.render.calls = 0;
  17384. this.compute.calls = 0;
  17385. this.render.timestamp = 0;
  17386. this.compute.timestamp = 0;
  17387. this.memory.geometries = 0;
  17388. this.memory.textures = 0;
  17389. }
  17390. }
  17391. /**
  17392. * Abstract class for representing pipelines.
  17393. *
  17394. * @private
  17395. * @abstract
  17396. */
  17397. class Pipeline {
  17398. /**
  17399. * Constructs a new pipeline.
  17400. *
  17401. * @param {String} cacheKey - The pipeline's cache key.
  17402. */
  17403. constructor( cacheKey ) {
  17404. /**
  17405. * The pipeline's cache key.
  17406. *
  17407. * @type {String}
  17408. */
  17409. this.cacheKey = cacheKey;
  17410. /**
  17411. * How often the pipeline is currently in use.
  17412. *
  17413. * @type {Number}
  17414. * @default 0
  17415. */
  17416. this.usedTimes = 0;
  17417. }
  17418. }
  17419. /**
  17420. * Class for representing render pipelines.
  17421. *
  17422. * @private
  17423. * @augments Pipeline
  17424. */
  17425. class RenderPipeline extends Pipeline {
  17426. /**
  17427. * Constructs a new render pipeline.
  17428. *
  17429. * @param {String} cacheKey - The pipeline's cache key.
  17430. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17431. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17432. */
  17433. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17434. super( cacheKey );
  17435. /**
  17436. * The pipeline's vertex shader.
  17437. *
  17438. * @type {ProgrammableStage}
  17439. */
  17440. this.vertexProgram = vertexProgram;
  17441. /**
  17442. * The pipeline's fragment shader.
  17443. *
  17444. * @type {ProgrammableStage}
  17445. */
  17446. this.fragmentProgram = fragmentProgram;
  17447. }
  17448. }
  17449. /**
  17450. * Class for representing compute pipelines.
  17451. *
  17452. * @private
  17453. * @augments Pipeline
  17454. */
  17455. class ComputePipeline extends Pipeline {
  17456. /**
  17457. * Constructs a new render pipeline.
  17458. *
  17459. * @param {String} cacheKey - The pipeline's cache key.
  17460. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17461. */
  17462. constructor( cacheKey, computeProgram ) {
  17463. super( cacheKey );
  17464. /**
  17465. * The pipeline's compute shader.
  17466. *
  17467. * @type {ProgrammableStage}
  17468. */
  17469. this.computeProgram = computeProgram;
  17470. /**
  17471. * This flag can be used for type testing.
  17472. *
  17473. * @type {Boolean}
  17474. * @readonly
  17475. * @default true
  17476. */
  17477. this.isComputePipeline = true;
  17478. }
  17479. }
  17480. let _id$8 = 0;
  17481. /**
  17482. * Class for representing programmable stages which are vertex,
  17483. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17484. * they represent the programmable part of a pipeline.
  17485. *
  17486. * @private
  17487. */
  17488. class ProgrammableStage {
  17489. /**
  17490. * Constructs a new programmable stage.
  17491. *
  17492. * @param {String} code - The shader code.
  17493. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17494. * @param {String} name - The name of the shader.
  17495. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17496. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17497. */
  17498. constructor( code, stage, name, transforms = null, attributes = null ) {
  17499. /**
  17500. * The id of the programmable stage.
  17501. *
  17502. * @type {Number}
  17503. */
  17504. this.id = _id$8 ++;
  17505. /**
  17506. * The shader code.
  17507. *
  17508. * @type {String}
  17509. */
  17510. this.code = code;
  17511. /**
  17512. * The type of stage.
  17513. *
  17514. * @type {String}
  17515. */
  17516. this.stage = stage;
  17517. /**
  17518. * The name of the stage.
  17519. * This is used for debugging purposes.
  17520. *
  17521. * @type {String}
  17522. */
  17523. this.name = name;
  17524. /**
  17525. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17526. *
  17527. * @type {Array<Object>?}
  17528. */
  17529. this.transforms = transforms;
  17530. /**
  17531. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17532. *
  17533. * @type {Array<Object>?}
  17534. */
  17535. this.attributes = attributes;
  17536. /**
  17537. * How often the programmable stage is currently in use.
  17538. *
  17539. * @type {Number}
  17540. * @default 0
  17541. */
  17542. this.usedTimes = 0;
  17543. }
  17544. }
  17545. /**
  17546. * This renderer module manages the pipelines of the renderer.
  17547. *
  17548. * @private
  17549. * @augments DataMap
  17550. */
  17551. class Pipelines extends DataMap {
  17552. /**
  17553. * Constructs a new pipeline management component.
  17554. *
  17555. * @param {Backend} backend - The renderer's backend.
  17556. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17557. */
  17558. constructor( backend, nodes ) {
  17559. super();
  17560. /**
  17561. * The renderer's backend.
  17562. *
  17563. * @type {Backend}
  17564. */
  17565. this.backend = backend;
  17566. /**
  17567. * Renderer component for managing nodes related logic.
  17568. *
  17569. * @type {Nodes}
  17570. */
  17571. this.nodes = nodes;
  17572. /**
  17573. * A references to the bindings management component.
  17574. * This reference will be set inside the `Bindings`
  17575. * constructor.
  17576. *
  17577. * @type {Bindings?}
  17578. * @default null
  17579. */
  17580. this.bindings = null;
  17581. /**
  17582. * Internal cache for maintaining pipelines.
  17583. * The key of the map is a cache key, the value the pipeline.
  17584. *
  17585. * @type {Map<String,Pipeline>}
  17586. */
  17587. this.caches = new Map();
  17588. /**
  17589. * This dictionary maintains for each shader stage type (vertex,
  17590. * fragment and compute) the programmable stage objects which
  17591. * represent the actual shader code.
  17592. *
  17593. * @type {Object<String,Map>}
  17594. */
  17595. this.programs = {
  17596. vertex: new Map(),
  17597. fragment: new Map(),
  17598. compute: new Map()
  17599. };
  17600. }
  17601. /**
  17602. * Returns a compute pipeline for the given compute node.
  17603. *
  17604. * @param {Node} computeNode - The compute node.
  17605. * @param {Array<BindGroup>} bindings - The bindings.
  17606. * @return {ComputePipeline} The compute pipeline.
  17607. */
  17608. getForCompute( computeNode, bindings ) {
  17609. const { backend } = this;
  17610. const data = this.get( computeNode );
  17611. if ( this._needsComputeUpdate( computeNode ) ) {
  17612. const previousPipeline = data.pipeline;
  17613. if ( previousPipeline ) {
  17614. previousPipeline.usedTimes --;
  17615. previousPipeline.computeProgram.usedTimes --;
  17616. }
  17617. // get shader
  17618. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17619. // programmable stage
  17620. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17621. if ( stageCompute === undefined ) {
  17622. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17623. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17624. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17625. backend.createProgram( stageCompute );
  17626. }
  17627. // determine compute pipeline
  17628. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17629. let pipeline = this.caches.get( cacheKey );
  17630. if ( pipeline === undefined ) {
  17631. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17632. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17633. }
  17634. // keep track of all used times
  17635. pipeline.usedTimes ++;
  17636. stageCompute.usedTimes ++;
  17637. //
  17638. data.version = computeNode.version;
  17639. data.pipeline = pipeline;
  17640. }
  17641. return data.pipeline;
  17642. }
  17643. /**
  17644. * Returns a render pipeline for the given render object.
  17645. *
  17646. * @param {RenderObject} renderObject - The render object.
  17647. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17648. * @return {RenderPipeline} The render pipeline.
  17649. */
  17650. getForRender( renderObject, promises = null ) {
  17651. const { backend } = this;
  17652. const data = this.get( renderObject );
  17653. if ( this._needsRenderUpdate( renderObject ) ) {
  17654. const previousPipeline = data.pipeline;
  17655. if ( previousPipeline ) {
  17656. previousPipeline.usedTimes --;
  17657. previousPipeline.vertexProgram.usedTimes --;
  17658. previousPipeline.fragmentProgram.usedTimes --;
  17659. }
  17660. // get shader
  17661. const nodeBuilderState = renderObject.getNodeBuilderState();
  17662. const name = renderObject.material ? renderObject.material.name : '';
  17663. // programmable stages
  17664. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17665. if ( stageVertex === undefined ) {
  17666. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17667. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17668. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17669. backend.createProgram( stageVertex );
  17670. }
  17671. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17672. if ( stageFragment === undefined ) {
  17673. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17674. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17675. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17676. backend.createProgram( stageFragment );
  17677. }
  17678. // determine render pipeline
  17679. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17680. let pipeline = this.caches.get( cacheKey );
  17681. if ( pipeline === undefined ) {
  17682. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17683. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17684. } else {
  17685. renderObject.pipeline = pipeline;
  17686. }
  17687. // keep track of all used times
  17688. pipeline.usedTimes ++;
  17689. stageVertex.usedTimes ++;
  17690. stageFragment.usedTimes ++;
  17691. //
  17692. data.pipeline = pipeline;
  17693. }
  17694. return data.pipeline;
  17695. }
  17696. /**
  17697. * Deletes the pipeline for the given render object.
  17698. *
  17699. * @param {RenderObject} object - The render object.
  17700. * @return {Object?} The deleted dictionary.
  17701. */
  17702. delete( object ) {
  17703. const pipeline = this.get( object ).pipeline;
  17704. if ( pipeline ) {
  17705. // pipeline
  17706. pipeline.usedTimes --;
  17707. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17708. // programs
  17709. if ( pipeline.isComputePipeline ) {
  17710. pipeline.computeProgram.usedTimes --;
  17711. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17712. } else {
  17713. pipeline.fragmentProgram.usedTimes --;
  17714. pipeline.vertexProgram.usedTimes --;
  17715. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17716. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17717. }
  17718. }
  17719. return super.delete( object );
  17720. }
  17721. /**
  17722. * Frees internal resources.
  17723. */
  17724. dispose() {
  17725. super.dispose();
  17726. this.caches = new Map();
  17727. this.programs = {
  17728. vertex: new Map(),
  17729. fragment: new Map(),
  17730. compute: new Map()
  17731. };
  17732. }
  17733. /**
  17734. * Updates the pipeline for the given render object.
  17735. *
  17736. * @param {RenderObject} renderObject - The render object.
  17737. */
  17738. updateForRender( renderObject ) {
  17739. this.getForRender( renderObject );
  17740. }
  17741. /**
  17742. * Returns a compute pipeline for the given parameters.
  17743. *
  17744. * @private
  17745. * @param {Node} computeNode - The compute node.
  17746. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17747. * @param {String} cacheKey - The cache key.
  17748. * @param {Array<BindGroup>} bindings - The bindings.
  17749. * @return {ComputePipeline} The compute pipeline.
  17750. */
  17751. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17752. // check for existing pipeline
  17753. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17754. let pipeline = this.caches.get( cacheKey );
  17755. if ( pipeline === undefined ) {
  17756. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17757. this.caches.set( cacheKey, pipeline );
  17758. this.backend.createComputePipeline( pipeline, bindings );
  17759. }
  17760. return pipeline;
  17761. }
  17762. /**
  17763. * Returns a render pipeline for the given parameters.
  17764. *
  17765. * @private
  17766. * @param {RenderObject} renderObject - The render object.
  17767. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17768. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17769. * @param {String} cacheKey - The cache key.
  17770. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17771. * @return {ComputePipeline} The compute pipeline.
  17772. */
  17773. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17774. // check for existing pipeline
  17775. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17776. let pipeline = this.caches.get( cacheKey );
  17777. if ( pipeline === undefined ) {
  17778. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17779. this.caches.set( cacheKey, pipeline );
  17780. renderObject.pipeline = pipeline;
  17781. // The `promises` array is `null` by default and only set to an empty array when
  17782. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17783. // pending promises that resolve when the render pipelines are ready for rendering.
  17784. this.backend.createRenderPipeline( renderObject, promises );
  17785. }
  17786. return pipeline;
  17787. }
  17788. /**
  17789. * Computes a cache key representing a compute pipeline.
  17790. *
  17791. * @private
  17792. * @param {Node} computeNode - The compute node.
  17793. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17794. * @return {String} The cache key.
  17795. */
  17796. _getComputeCacheKey( computeNode, stageCompute ) {
  17797. return computeNode.id + ',' + stageCompute.id;
  17798. }
  17799. /**
  17800. * Computes a cache key representing a render pipeline.
  17801. *
  17802. * @private
  17803. * @param {RenderObject} renderObject - The render object.
  17804. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17805. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17806. * @return {String} The cache key.
  17807. */
  17808. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17809. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17810. }
  17811. /**
  17812. * Releases the given pipeline.
  17813. *
  17814. * @private
  17815. * @param {Pipeline} pipeline - The pipeline to release.
  17816. */
  17817. _releasePipeline( pipeline ) {
  17818. this.caches.delete( pipeline.cacheKey );
  17819. }
  17820. /**
  17821. * Releases the shader program.
  17822. *
  17823. * @private
  17824. * @param {Object} program - The shader program to release.
  17825. */
  17826. _releaseProgram( program ) {
  17827. const code = program.code;
  17828. const stage = program.stage;
  17829. this.programs[ stage ].delete( code );
  17830. }
  17831. /**
  17832. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17833. *
  17834. * @private
  17835. * @param {Node} computeNode - The compute node.
  17836. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17837. */
  17838. _needsComputeUpdate( computeNode ) {
  17839. const data = this.get( computeNode );
  17840. return data.pipeline === undefined || data.version !== computeNode.version;
  17841. }
  17842. /**
  17843. * Returns `true` if the render pipeline for the given render object requires an update.
  17844. *
  17845. * @private
  17846. * @param {RenderObject} renderObject - The render object.
  17847. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17848. */
  17849. _needsRenderUpdate( renderObject ) {
  17850. const data = this.get( renderObject );
  17851. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17852. }
  17853. }
  17854. /**
  17855. * This renderer module manages the bindings of the renderer.
  17856. *
  17857. * @private
  17858. * @augments DataMap
  17859. */
  17860. class Bindings extends DataMap {
  17861. /**
  17862. * Constructs a new bindings management component.
  17863. *
  17864. * @param {Backend} backend - The renderer's backend.
  17865. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17866. * @param {Textures} textures - Renderer component for managing textures.
  17867. * @param {Attributes} attributes - Renderer component for managing attributes.
  17868. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17869. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17870. */
  17871. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17872. super();
  17873. /**
  17874. * The renderer's backend.
  17875. *
  17876. * @type {Backend}
  17877. */
  17878. this.backend = backend;
  17879. /**
  17880. * Renderer component for managing textures.
  17881. *
  17882. * @type {Textures}
  17883. */
  17884. this.textures = textures;
  17885. /**
  17886. * Renderer component for managing pipelines.
  17887. *
  17888. * @type {Pipelines}
  17889. */
  17890. this.pipelines = pipelines;
  17891. /**
  17892. * Renderer component for managing attributes.
  17893. *
  17894. * @type {Attributes}
  17895. */
  17896. this.attributes = attributes;
  17897. /**
  17898. * Renderer component for managing nodes related logic.
  17899. *
  17900. * @type {Nodes}
  17901. */
  17902. this.nodes = nodes;
  17903. /**
  17904. * Renderer component for managing metrics and monitoring data.
  17905. *
  17906. * @type {Info}
  17907. */
  17908. this.info = info;
  17909. this.pipelines.bindings = this; // assign bindings to pipelines
  17910. }
  17911. /**
  17912. * Returns the bind groups for the given render object.
  17913. *
  17914. * @param {RenderObject} renderObject - The render object.
  17915. * @return {Array<BindGroup>} The bind groups.
  17916. */
  17917. getForRender( renderObject ) {
  17918. const bindings = renderObject.getBindings();
  17919. for ( const bindGroup of bindings ) {
  17920. const groupData = this.get( bindGroup );
  17921. if ( groupData.bindGroup === undefined ) {
  17922. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17923. this._init( bindGroup );
  17924. this.backend.createBindings( bindGroup, bindings, 0 );
  17925. groupData.bindGroup = bindGroup;
  17926. }
  17927. }
  17928. return bindings;
  17929. }
  17930. /**
  17931. * Returns the bind groups for the given compute node.
  17932. *
  17933. * @param {Node} computeNode - The compute node.
  17934. * @return {Array<BindGroup>} The bind groups.
  17935. */
  17936. getForCompute( computeNode ) {
  17937. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17938. for ( const bindGroup of bindings ) {
  17939. const groupData = this.get( bindGroup );
  17940. if ( groupData.bindGroup === undefined ) {
  17941. this._init( bindGroup );
  17942. this.backend.createBindings( bindGroup, bindings, 0 );
  17943. groupData.bindGroup = bindGroup;
  17944. }
  17945. }
  17946. return bindings;
  17947. }
  17948. /**
  17949. * Updates the bindings for the given compute node.
  17950. *
  17951. * @param {Node} computeNode - The compute node.
  17952. */
  17953. updateForCompute( computeNode ) {
  17954. this._updateBindings( this.getForCompute( computeNode ) );
  17955. }
  17956. /**
  17957. * Updates the bindings for the given render object.
  17958. *
  17959. * @param {RenderObject} renderObject - The render object.
  17960. */
  17961. updateForRender( renderObject ) {
  17962. this._updateBindings( this.getForRender( renderObject ) );
  17963. }
  17964. /**
  17965. * Updates the given array of bindings.
  17966. *
  17967. * @param {Array<BindGroup>} bindings - The bind groups.
  17968. */
  17969. _updateBindings( bindings ) {
  17970. for ( const bindGroup of bindings ) {
  17971. this._update( bindGroup, bindings );
  17972. }
  17973. }
  17974. /**
  17975. * Initializes the given bind group.
  17976. *
  17977. * @param {BindGroup} bindGroup - The bind group to initialize.
  17978. */
  17979. _init( bindGroup ) {
  17980. for ( const binding of bindGroup.bindings ) {
  17981. if ( binding.isSampledTexture ) {
  17982. this.textures.updateTexture( binding.texture );
  17983. } else if ( binding.isStorageBuffer ) {
  17984. const attribute = binding.attribute;
  17985. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17986. this.attributes.update( attribute, attributeType );
  17987. }
  17988. }
  17989. }
  17990. /**
  17991. * Updates the given bind group.
  17992. *
  17993. * @param {BindGroup} bindGroup - The bind group to update.
  17994. * @param {Array<BindGroup>} bindings - The bind groups.
  17995. */
  17996. _update( bindGroup, bindings ) {
  17997. const { backend } = this;
  17998. let needsBindingsUpdate = false;
  17999. let cacheBindings = true;
  18000. let cacheIndex = 0;
  18001. let version = 0;
  18002. // iterate over all bindings and check if buffer updates or a new binding group is required
  18003. for ( const binding of bindGroup.bindings ) {
  18004. if ( binding.isNodeUniformsGroup ) {
  18005. const updated = this.nodes.updateGroup( binding );
  18006. // every uniforms group is a uniform buffer. So if no update is required,
  18007. // we move one with the next binding. Otherwise the next if block will update the group.
  18008. if ( updated === false ) continue;
  18009. }
  18010. if ( binding.isUniformBuffer ) {
  18011. const updated = binding.update();
  18012. if ( updated ) {
  18013. backend.updateBinding( binding );
  18014. }
  18015. } else if ( binding.isSampler ) {
  18016. binding.update();
  18017. } else if ( binding.isSampledTexture ) {
  18018. const texturesTextureData = this.textures.get( binding.texture );
  18019. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18020. const updated = binding.update();
  18021. const texture = binding.texture;
  18022. if ( updated ) {
  18023. this.textures.updateTexture( texture );
  18024. }
  18025. const textureData = backend.get( texture );
  18026. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18027. cacheBindings = false;
  18028. } else {
  18029. cacheIndex = cacheIndex * 10 + texture.id;
  18030. version += texture.version;
  18031. }
  18032. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18033. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18034. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18035. this.textures.updateTexture( texture );
  18036. needsBindingsUpdate = true;
  18037. }
  18038. if ( texture.isStorageTexture === true ) {
  18039. const textureData = this.get( texture );
  18040. if ( binding.store === true ) {
  18041. textureData.needsMipmap = true;
  18042. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18043. this.backend.generateMipmaps( texture );
  18044. textureData.needsMipmap = false;
  18045. }
  18046. }
  18047. }
  18048. }
  18049. if ( needsBindingsUpdate === true ) {
  18050. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18051. }
  18052. }
  18053. }
  18054. /**
  18055. * Default sorting function for opaque render items.
  18056. *
  18057. * @private
  18058. * @function
  18059. * @param {Object} a - The first render item.
  18060. * @param {Object} b - The second render item.
  18061. * @return {Number} A numeric value which defines the sort order.
  18062. */
  18063. function painterSortStable( a, b ) {
  18064. if ( a.groupOrder !== b.groupOrder ) {
  18065. return a.groupOrder - b.groupOrder;
  18066. } else if ( a.renderOrder !== b.renderOrder ) {
  18067. return a.renderOrder - b.renderOrder;
  18068. } else if ( a.material.id !== b.material.id ) {
  18069. return a.material.id - b.material.id;
  18070. } else if ( a.z !== b.z ) {
  18071. return a.z - b.z;
  18072. } else {
  18073. return a.id - b.id;
  18074. }
  18075. }
  18076. /**
  18077. * Default sorting function for transparent render items.
  18078. *
  18079. * @private
  18080. * @function
  18081. * @param {Object} a - The first render item.
  18082. * @param {Object} b - The second render item.
  18083. * @return {Number} A numeric value which defines the sort order.
  18084. */
  18085. function reversePainterSortStable( a, b ) {
  18086. if ( a.groupOrder !== b.groupOrder ) {
  18087. return a.groupOrder - b.groupOrder;
  18088. } else if ( a.renderOrder !== b.renderOrder ) {
  18089. return a.renderOrder - b.renderOrder;
  18090. } else if ( a.z !== b.z ) {
  18091. return b.z - a.z;
  18092. } else {
  18093. return a.id - b.id;
  18094. }
  18095. }
  18096. /**
  18097. * Returns `true` if the given transparent material requires a double pass.
  18098. *
  18099. * @private
  18100. * @function
  18101. * @param {Material} material - The transparent material.
  18102. * @return {Boolean} Whether the given material requires a double pass or not.
  18103. */
  18104. function needsDoublePass( material ) {
  18105. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18106. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18107. }
  18108. /**
  18109. * When the renderer analyzes the scene at the beginning of a render call,
  18110. * it stores 3D object for further processing in render lists. Depending on the
  18111. * properties of a 3D objects (like their transformation or material state), the
  18112. * objects are maintained in ordered lists for the actual rendering.
  18113. *
  18114. * Render lists are unique per scene and camera combination.
  18115. *
  18116. * @private
  18117. * @augments Pipeline
  18118. */
  18119. class RenderList {
  18120. /**
  18121. * Constructs a render list.
  18122. *
  18123. * @param {Lighting} lighting - The lighting management component.
  18124. * @param {Scene} scene - The scene.
  18125. * @param {Camera} camera - The camera the scene is rendered with.
  18126. */
  18127. constructor( lighting, scene, camera ) {
  18128. /**
  18129. * 3D objects are transformed into render items and stored in this array.
  18130. *
  18131. * @type {Array<Object>}
  18132. */
  18133. this.renderItems = [];
  18134. /**
  18135. * The current render items index.
  18136. *
  18137. * @type {Number}
  18138. * @default 0
  18139. */
  18140. this.renderItemsIndex = 0;
  18141. /**
  18142. * A list with opaque render items.
  18143. *
  18144. * @type {Array<Object>}
  18145. */
  18146. this.opaque = [];
  18147. /**
  18148. * A list with transparent render items which require
  18149. * double pass rendering (e.g. transmissive objects).
  18150. *
  18151. * @type {Array<Object>}
  18152. */
  18153. this.transparentDoublePass = [];
  18154. /**
  18155. * A list with transparent render items.
  18156. *
  18157. * @type {Array<Object>}
  18158. */
  18159. this.transparent = [];
  18160. /**
  18161. * A list with transparent render bundle data.
  18162. *
  18163. * @type {Array<Object>}
  18164. */
  18165. this.bundles = [];
  18166. /**
  18167. * The render list's lights node. This node is later
  18168. * relevant for the actual analytical light nodes which
  18169. * compute the scene's lighting in the shader.
  18170. *
  18171. * @type {LightsNode}
  18172. */
  18173. this.lightsNode = lighting.getNode( scene, camera );
  18174. /**
  18175. * The scene's lights stored in an array. This array
  18176. * is used to setup the lights node.
  18177. *
  18178. * @type {Array<Light>}
  18179. */
  18180. this.lightsArray = [];
  18181. /**
  18182. * The scene.
  18183. *
  18184. * @type {Scene}
  18185. */
  18186. this.scene = scene;
  18187. /**
  18188. * The camera the scene is rendered with.
  18189. *
  18190. * @type {Camera}
  18191. */
  18192. this.camera = camera;
  18193. /**
  18194. * How many objects perform occlusion query tests.
  18195. *
  18196. * @type {Number}
  18197. * @default 0
  18198. */
  18199. this.occlusionQueryCount = 0;
  18200. }
  18201. /**
  18202. * This method is called right at the beginning of a render call
  18203. * before the scene is analyzed. It prepares the internal data
  18204. * structures for the upcoming render lists generation.
  18205. *
  18206. * @return {RenderList} A reference to this render list.
  18207. */
  18208. begin() {
  18209. this.renderItemsIndex = 0;
  18210. this.opaque.length = 0;
  18211. this.transparentDoublePass.length = 0;
  18212. this.transparent.length = 0;
  18213. this.bundles.length = 0;
  18214. this.lightsArray.length = 0;
  18215. this.occlusionQueryCount = 0;
  18216. return this;
  18217. }
  18218. /**
  18219. * Returns a render item for the giving render item state. The state is defined
  18220. * by a series of object-related parameters.
  18221. *
  18222. * The method avoids object creation by holding render items and reusing them in
  18223. * subsequent render calls (just with different property values).
  18224. *
  18225. * @param {Object3D} object - The 3D object.
  18226. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18227. * @param {Material} material - The 3D object's material.
  18228. * @param {Number} groupOrder - The current group order.
  18229. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18230. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18231. * @param {ClippingContext} clippingContext - The current clipping context.
  18232. * @return {Object} The render item.
  18233. */
  18234. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18235. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18236. if ( renderItem === undefined ) {
  18237. renderItem = {
  18238. id: object.id,
  18239. object: object,
  18240. geometry: geometry,
  18241. material: material,
  18242. groupOrder: groupOrder,
  18243. renderOrder: object.renderOrder,
  18244. z: z,
  18245. group: group,
  18246. clippingContext: clippingContext
  18247. };
  18248. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18249. } else {
  18250. renderItem.id = object.id;
  18251. renderItem.object = object;
  18252. renderItem.geometry = geometry;
  18253. renderItem.material = material;
  18254. renderItem.groupOrder = groupOrder;
  18255. renderItem.renderOrder = object.renderOrder;
  18256. renderItem.z = z;
  18257. renderItem.group = group;
  18258. renderItem.clippingContext = clippingContext;
  18259. }
  18260. this.renderItemsIndex ++;
  18261. return renderItem;
  18262. }
  18263. /**
  18264. * Pushes the given object as a render item to the internal render lists.
  18265. * The selected lists depend on the object properties.
  18266. *
  18267. * @param {Object3D} object - The 3D object.
  18268. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18269. * @param {Material} material - The 3D object's material.
  18270. * @param {Number} groupOrder - The current group order.
  18271. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18272. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18273. * @param {ClippingContext} clippingContext - The current clipping context.
  18274. */
  18275. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18276. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18277. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18278. if ( material.transparent === true || material.transmission > 0 ) {
  18279. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18280. this.transparent.push( renderItem );
  18281. } else {
  18282. this.opaque.push( renderItem );
  18283. }
  18284. }
  18285. /**
  18286. * Inserts the given object as a render item at the start of the internal render lists.
  18287. * The selected lists depend on the object properties.
  18288. *
  18289. * @param {Object3D} object - The 3D object.
  18290. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18291. * @param {Material} material - The 3D object's material.
  18292. * @param {Number} groupOrder - The current group order.
  18293. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18294. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18295. * @param {ClippingContext} clippingContext - The current clipping context.
  18296. */
  18297. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18298. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18299. if ( material.transparent === true || material.transmission > 0 ) {
  18300. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18301. this.transparent.unshift( renderItem );
  18302. } else {
  18303. this.opaque.unshift( renderItem );
  18304. }
  18305. }
  18306. /**
  18307. * Pushes render bundle group data into the render list.
  18308. *
  18309. * @param {Object} group - Bundle group data.
  18310. */
  18311. pushBundle( group ) {
  18312. this.bundles.push( group );
  18313. }
  18314. /**
  18315. * Pushes a light into the render list.
  18316. *
  18317. * @param {Light} light - The light.
  18318. */
  18319. pushLight( light ) {
  18320. this.lightsArray.push( light );
  18321. }
  18322. /**
  18323. * Sorts the internal render lists.
  18324. *
  18325. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18326. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18327. */
  18328. sort( customOpaqueSort, customTransparentSort ) {
  18329. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18330. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18331. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18332. }
  18333. /**
  18334. * This method performs finalizing tasks right after the render lists
  18335. * have been generated.
  18336. */
  18337. finish() {
  18338. // update lights
  18339. this.lightsNode.setLights( this.lightsArray );
  18340. // Clear references from inactive renderItems in the list
  18341. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18342. const renderItem = this.renderItems[ i ];
  18343. if ( renderItem.id === null ) break;
  18344. renderItem.id = null;
  18345. renderItem.object = null;
  18346. renderItem.geometry = null;
  18347. renderItem.material = null;
  18348. renderItem.groupOrder = null;
  18349. renderItem.renderOrder = null;
  18350. renderItem.z = null;
  18351. renderItem.group = null;
  18352. renderItem.clippingContext = null;
  18353. }
  18354. }
  18355. }
  18356. const _chainKeys$4 = [];
  18357. /**
  18358. * This renderer module manages the render lists which are unique
  18359. * per scene and camera combination.
  18360. *
  18361. * @private
  18362. */
  18363. class RenderLists {
  18364. /**
  18365. * Constructs a render lists management component.
  18366. *
  18367. * @param {Lighting} lighting - The lighting management component.
  18368. */
  18369. constructor( lighting ) {
  18370. /**
  18371. * The lighting management component.
  18372. *
  18373. * @type {Lighting}
  18374. */
  18375. this.lighting = lighting;
  18376. /**
  18377. * The internal chain map which holds the render lists.
  18378. *
  18379. * @type {ChainMap}
  18380. */
  18381. this.lists = new ChainMap();
  18382. }
  18383. /**
  18384. * Returns a render list for the given scene and camera.
  18385. *
  18386. * @param {Scene} scene - The scene.
  18387. * @param {Camera} camera - The camera.
  18388. * @return {RenderList} The render list.
  18389. */
  18390. get( scene, camera ) {
  18391. const lists = this.lists;
  18392. _chainKeys$4[ 0 ] = scene;
  18393. _chainKeys$4[ 1 ] = camera;
  18394. let list = lists.get( _chainKeys$4 );
  18395. if ( list === undefined ) {
  18396. list = new RenderList( this.lighting, scene, camera );
  18397. lists.set( _chainKeys$4, list );
  18398. }
  18399. _chainKeys$4.length = 0;
  18400. return list;
  18401. }
  18402. /**
  18403. * Frees all internal resources.
  18404. */
  18405. dispose() {
  18406. this.lists = new ChainMap();
  18407. }
  18408. }
  18409. let _id$7 = 0;
  18410. /**
  18411. * Any render or compute command is executed in a specific context that defines
  18412. * the state of the renderer and its backend. Typical examples for such context
  18413. * data are the current clear values or data from the active framebuffer. This
  18414. * module is used to represent these contexts as objects.
  18415. *
  18416. * @private
  18417. */
  18418. class RenderContext {
  18419. /**
  18420. * Constructs a new render context.
  18421. */
  18422. constructor() {
  18423. /**
  18424. * The context's ID.
  18425. *
  18426. * @type {Number}
  18427. */
  18428. this.id = _id$7 ++;
  18429. /**
  18430. * Whether the current active framebuffer has a color attachment.
  18431. *
  18432. * @type {Boolean}
  18433. * @default true
  18434. */
  18435. this.color = true;
  18436. /**
  18437. * Whether the color attachment should be cleared or not.
  18438. *
  18439. * @type {Boolean}
  18440. * @default true
  18441. */
  18442. this.clearColor = true;
  18443. /**
  18444. * The clear color value.
  18445. *
  18446. * @type {Object}
  18447. * @default true
  18448. */
  18449. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18450. /**
  18451. * Whether the current active framebuffer has a depth attachment.
  18452. *
  18453. * @type {Boolean}
  18454. * @default true
  18455. */
  18456. this.depth = true;
  18457. /**
  18458. * Whether the depth attachment should be cleared or not.
  18459. *
  18460. * @type {Boolean}
  18461. * @default true
  18462. */
  18463. this.clearDepth = true;
  18464. /**
  18465. * The clear depth value.
  18466. *
  18467. * @type {Number}
  18468. * @default 1
  18469. */
  18470. this.clearDepthValue = 1;
  18471. /**
  18472. * Whether the current active framebuffer has a stencil attachment.
  18473. *
  18474. * @type {Boolean}
  18475. * @default false
  18476. */
  18477. this.stencil = false;
  18478. /**
  18479. * Whether the stencil attachment should be cleared or not.
  18480. *
  18481. * @type {Boolean}
  18482. * @default true
  18483. */
  18484. this.clearStencil = true;
  18485. /**
  18486. * The clear stencil value.
  18487. *
  18488. * @type {Number}
  18489. * @default 1
  18490. */
  18491. this.clearStencilValue = 1;
  18492. /**
  18493. * By default the viewport encloses the entire framebuffer If a smaller
  18494. * viewport is manually defined, this property is to `true` by the renderer.
  18495. *
  18496. * @type {Boolean}
  18497. * @default false
  18498. */
  18499. this.viewport = false;
  18500. /**
  18501. * The viewport value. This value is in physical pixels meaning it incorporates
  18502. * the renderer's pixel ratio. The viewport property of render targets or
  18503. * the renderer is in logical pixels.
  18504. *
  18505. * @type {Vector4}
  18506. */
  18507. this.viewportValue = new Vector4();
  18508. /**
  18509. * When the scissor test is active and scissor rectangle smaller than the
  18510. * framebuffers dimensions, this property is to `true` by the renderer.
  18511. *
  18512. * @type {Boolean}
  18513. * @default false
  18514. */
  18515. this.scissor = false;
  18516. /**
  18517. * The scissor rectangle.
  18518. *
  18519. * @type {Vector4}
  18520. */
  18521. this.scissorValue = new Vector4();
  18522. /**
  18523. * The active render target.
  18524. *
  18525. * @type {RenderTarget?}
  18526. * @default null
  18527. */
  18528. this.renderTarget = null;
  18529. /**
  18530. * The textures of the active render target.
  18531. * `null` when no render target is set.
  18532. *
  18533. * @type {Array<Texture>?}
  18534. * @default null
  18535. */
  18536. this.textures = null;
  18537. /**
  18538. * The depth texture of the active render target.
  18539. * `null` when no render target is set.
  18540. *
  18541. * @type {DepthTexture?}
  18542. * @default null
  18543. */
  18544. this.depthTexture = null;
  18545. /**
  18546. * The active cube face.
  18547. *
  18548. * @type {Number}
  18549. * @default 0
  18550. */
  18551. this.activeCubeFace = 0;
  18552. /**
  18553. * The active mipmap level.
  18554. *
  18555. * @type {Number}
  18556. * @default 0
  18557. */
  18558. this.activeMipmapLevel = 0;
  18559. /**
  18560. * The number of MSAA samples. This value is always `1` when
  18561. * MSAA isn't used.
  18562. *
  18563. * @type {Number}
  18564. * @default 1
  18565. */
  18566. this.sampleCount = 1;
  18567. /**
  18568. * The active render target's width in physical pixels.
  18569. *
  18570. * @type {Number}
  18571. * @default 0
  18572. */
  18573. this.width = 0;
  18574. /**
  18575. * The active render target's height in physical pixels.
  18576. *
  18577. * @type {Number}
  18578. * @default 0
  18579. */
  18580. this.height = 0;
  18581. /**
  18582. * The occlusion query count.
  18583. *
  18584. * @type {Number}
  18585. * @default 0
  18586. */
  18587. this.occlusionQueryCount = 0;
  18588. /**
  18589. * The current clipping context.
  18590. *
  18591. * @type {ClippingContext?}
  18592. * @default null
  18593. */
  18594. this.clippingContext = null;
  18595. /**
  18596. * This flag can be used for type testing.
  18597. *
  18598. * @type {Boolean}
  18599. * @readonly
  18600. * @default true
  18601. */
  18602. this.isRenderContext = true;
  18603. }
  18604. /**
  18605. * Returns the cache key of this render context.
  18606. *
  18607. * @return {Number} The cache key.
  18608. */
  18609. getCacheKey() {
  18610. return getCacheKey( this );
  18611. }
  18612. }
  18613. /**
  18614. * Computes a cache key for the given render context. This key
  18615. * should identify the render target state so it is possible to
  18616. * configure the correct attachments in the respective backend.
  18617. *
  18618. * @param {RenderContext} renderContext - The render context.
  18619. * @return {Number} The cache key.
  18620. */
  18621. function getCacheKey( renderContext ) {
  18622. const { textures, activeCubeFace } = renderContext;
  18623. const values = [ activeCubeFace ];
  18624. for ( const texture of textures ) {
  18625. values.push( texture.id );
  18626. }
  18627. return hashArray( values );
  18628. }
  18629. const _chainKeys$3 = [];
  18630. const _defaultScene = /*@__PURE__*/ new Scene();
  18631. const _defaultCamera = /*@__PURE__*/ new Camera();
  18632. /**
  18633. * This module manages the render contexts of the renderer.
  18634. *
  18635. * @private
  18636. */
  18637. class RenderContexts {
  18638. /**
  18639. * Constructs a new render context management component.
  18640. */
  18641. constructor() {
  18642. /**
  18643. * A dictionary that manages render contexts in chain maps
  18644. * for each attachment state.
  18645. *
  18646. * @type {Object<String,ChainMap>}
  18647. */
  18648. this.chainMaps = {};
  18649. }
  18650. /**
  18651. * Returns a render context for the given scene, camera and render target.
  18652. *
  18653. * @param {Scene} scene - The scene.
  18654. * @param {Camera} camera - The camera that is used to render the scene.
  18655. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18656. * @return {RenderContext} The render context.
  18657. */
  18658. get( scene, camera, renderTarget = null ) {
  18659. _chainKeys$3[ 0 ] = scene;
  18660. _chainKeys$3[ 1 ] = camera;
  18661. let attachmentState;
  18662. if ( renderTarget === null ) {
  18663. attachmentState = 'default';
  18664. } else {
  18665. const format = renderTarget.texture.format;
  18666. const count = renderTarget.textures.length;
  18667. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18668. }
  18669. const chainMap = this._getChainMap( attachmentState );
  18670. let renderState = chainMap.get( _chainKeys$3 );
  18671. if ( renderState === undefined ) {
  18672. renderState = new RenderContext();
  18673. chainMap.set( _chainKeys$3, renderState );
  18674. }
  18675. _chainKeys$3.length = 0;
  18676. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18677. return renderState;
  18678. }
  18679. /**
  18680. * Returns a render context intended for clear operations.
  18681. *
  18682. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18683. * @return {RenderContext} The render context.
  18684. */
  18685. getForClear( renderTarget = null ) {
  18686. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18687. }
  18688. /**
  18689. * Returns a chain map for the given attachment state.
  18690. *
  18691. * @private
  18692. * @param {String} attachmentState - The attachment state.
  18693. * @return {ChainMap} The chain map.
  18694. */
  18695. _getChainMap( attachmentState ) {
  18696. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18697. }
  18698. /**
  18699. * Frees internal resources.
  18700. */
  18701. dispose() {
  18702. this.chainMaps = {};
  18703. }
  18704. }
  18705. const _size$3 = /*@__PURE__*/ new Vector3();
  18706. /**
  18707. * This module manages the textures of the renderer.
  18708. *
  18709. * @private
  18710. * @augments DataMap
  18711. */
  18712. class Textures extends DataMap {
  18713. /**
  18714. * Constructs a new texture management component.
  18715. *
  18716. * @param {Renderer} renderer - The renderer.
  18717. * @param {Backend} backend - The renderer's backend.
  18718. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18719. */
  18720. constructor( renderer, backend, info ) {
  18721. super();
  18722. /**
  18723. * The renderer.
  18724. *
  18725. * @type {Renderer}
  18726. */
  18727. this.renderer = renderer;
  18728. /**
  18729. * The backend.
  18730. *
  18731. * @type {Backend}
  18732. */
  18733. this.backend = backend;
  18734. /**
  18735. * Renderer component for managing metrics and monitoring data.
  18736. *
  18737. * @type {Info}
  18738. */
  18739. this.info = info;
  18740. }
  18741. /**
  18742. * Updates the given render target. Based on the given render target configuration,
  18743. * it updates the texture states representing the attachments of the framebuffer.
  18744. *
  18745. * @param {RenderTarget} renderTarget - The render target to update.
  18746. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18747. */
  18748. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18749. const renderTargetData = this.get( renderTarget );
  18750. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18751. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18752. const textures = renderTarget.textures;
  18753. const size = this.getSize( textures[ 0 ] );
  18754. const mipWidth = size.width >> activeMipmapLevel;
  18755. const mipHeight = size.height >> activeMipmapLevel;
  18756. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18757. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18758. let textureNeedsUpdate = false;
  18759. if ( depthTexture === undefined && useDepthTexture ) {
  18760. depthTexture = new DepthTexture();
  18761. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18762. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18763. depthTexture.image.width = mipWidth;
  18764. depthTexture.image.height = mipHeight;
  18765. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18766. }
  18767. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18768. textureNeedsUpdate = true;
  18769. if ( depthTexture ) {
  18770. depthTexture.needsUpdate = true;
  18771. depthTexture.image.width = mipWidth;
  18772. depthTexture.image.height = mipHeight;
  18773. }
  18774. }
  18775. renderTargetData.width = size.width;
  18776. renderTargetData.height = size.height;
  18777. renderTargetData.textures = textures;
  18778. renderTargetData.depthTexture = depthTexture || null;
  18779. renderTargetData.depth = renderTarget.depthBuffer;
  18780. renderTargetData.stencil = renderTarget.stencilBuffer;
  18781. renderTargetData.renderTarget = renderTarget;
  18782. if ( renderTargetData.sampleCount !== sampleCount ) {
  18783. textureNeedsUpdate = true;
  18784. if ( depthTexture ) {
  18785. depthTexture.needsUpdate = true;
  18786. }
  18787. renderTargetData.sampleCount = sampleCount;
  18788. }
  18789. //
  18790. const options = { sampleCount };
  18791. for ( let i = 0; i < textures.length; i ++ ) {
  18792. const texture = textures[ i ];
  18793. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18794. this.updateTexture( texture, options );
  18795. }
  18796. if ( depthTexture ) {
  18797. this.updateTexture( depthTexture, options );
  18798. }
  18799. // dispose handler
  18800. if ( renderTargetData.initialized !== true ) {
  18801. renderTargetData.initialized = true;
  18802. // dispose
  18803. const onDispose = () => {
  18804. renderTarget.removeEventListener( 'dispose', onDispose );
  18805. for ( let i = 0; i < textures.length; i ++ ) {
  18806. this._destroyTexture( textures[ i ] );
  18807. }
  18808. if ( depthTexture ) {
  18809. this._destroyTexture( depthTexture );
  18810. }
  18811. this.delete( renderTarget );
  18812. };
  18813. renderTarget.addEventListener( 'dispose', onDispose );
  18814. }
  18815. }
  18816. /**
  18817. * Updates the given texture. Depending on the texture state, this method
  18818. * triggers the upload of texture data to the GPU memory. If the texture data are
  18819. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18820. *
  18821. * @param {Texture} texture - The texture to update.
  18822. * @param {Object} [options={}] - The options.
  18823. */
  18824. updateTexture( texture, options = {} ) {
  18825. const textureData = this.get( texture );
  18826. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18827. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18828. const backend = this.backend;
  18829. if ( isRenderTarget && textureData.initialized === true ) {
  18830. // it's an update
  18831. backend.destroySampler( texture );
  18832. backend.destroyTexture( texture );
  18833. }
  18834. //
  18835. if ( texture.isFramebufferTexture ) {
  18836. const renderTarget = this.renderer.getRenderTarget();
  18837. if ( renderTarget ) {
  18838. texture.type = renderTarget.texture.type;
  18839. } else {
  18840. texture.type = UnsignedByteType;
  18841. }
  18842. }
  18843. //
  18844. const { width, height, depth } = this.getSize( texture );
  18845. options.width = width;
  18846. options.height = height;
  18847. options.depth = depth;
  18848. options.needsMipmaps = this.needsMipmaps( texture );
  18849. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18850. //
  18851. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18852. backend.createSampler( texture );
  18853. backend.createTexture( texture, options );
  18854. textureData.generation = texture.version;
  18855. } else {
  18856. const needsCreate = textureData.initialized !== true;
  18857. if ( needsCreate ) backend.createSampler( texture );
  18858. if ( texture.version > 0 ) {
  18859. const image = texture.image;
  18860. if ( image === undefined ) {
  18861. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18862. } else if ( image.complete === false ) {
  18863. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18864. } else {
  18865. if ( texture.images ) {
  18866. const images = [];
  18867. for ( const image of texture.images ) {
  18868. images.push( image );
  18869. }
  18870. options.images = images;
  18871. } else {
  18872. options.image = image;
  18873. }
  18874. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18875. backend.createTexture( texture, options );
  18876. textureData.isDefaultTexture = false;
  18877. textureData.generation = texture.version;
  18878. }
  18879. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18880. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18881. }
  18882. } else {
  18883. // async update
  18884. backend.createDefaultTexture( texture );
  18885. textureData.isDefaultTexture = true;
  18886. textureData.generation = texture.version;
  18887. }
  18888. }
  18889. // dispose handler
  18890. if ( textureData.initialized !== true ) {
  18891. textureData.initialized = true;
  18892. textureData.generation = texture.version;
  18893. //
  18894. this.info.memory.textures ++;
  18895. // dispose
  18896. const onDispose = () => {
  18897. texture.removeEventListener( 'dispose', onDispose );
  18898. this._destroyTexture( texture );
  18899. this.info.memory.textures --;
  18900. };
  18901. texture.addEventListener( 'dispose', onDispose );
  18902. }
  18903. //
  18904. textureData.version = texture.version;
  18905. }
  18906. /**
  18907. * Computes the size of the given texture and writes the result
  18908. * into the target vector. This vector is also returned by the
  18909. * method.
  18910. *
  18911. * If no texture data are available for the compute yet, the method
  18912. * returns default size values.
  18913. *
  18914. * @param {Texture} texture - The texture to compute the size for.
  18915. * @param {Vector3} target - The target vector.
  18916. * @return {Vector3} The target vector.
  18917. */
  18918. getSize( texture, target = _size$3 ) {
  18919. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18920. if ( image ) {
  18921. if ( image.image !== undefined ) image = image.image;
  18922. target.width = image.width || 1;
  18923. target.height = image.height || 1;
  18924. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18925. } else {
  18926. target.width = target.height = target.depth = 1;
  18927. }
  18928. return target;
  18929. }
  18930. /**
  18931. * Computes the number of mipmap levels for the given texture.
  18932. *
  18933. * @param {Texture} texture - The texture.
  18934. * @param {Number} width - The texture's width.
  18935. * @param {Number} height - The texture's height.
  18936. * @return {Number} The number of mipmap levels.
  18937. */
  18938. getMipLevels( texture, width, height ) {
  18939. let mipLevelCount;
  18940. if ( texture.isCompressedTexture ) {
  18941. if ( texture.mipmaps ) {
  18942. mipLevelCount = texture.mipmaps.length;
  18943. } else {
  18944. mipLevelCount = 1;
  18945. }
  18946. } else {
  18947. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18948. }
  18949. return mipLevelCount;
  18950. }
  18951. /**
  18952. * Returns `true` if the given texture requires mipmaps.
  18953. *
  18954. * @param {Texture} texture - The texture.
  18955. * @return {Boolean} Whether mipmaps are required or not.
  18956. */
  18957. needsMipmaps( texture ) {
  18958. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18959. }
  18960. /**
  18961. * Returns `true` if the given texture is an environment map.
  18962. *
  18963. * @param {Texture} texture - The texture.
  18964. * @return {Boolean} Whether the given texture is an environment map or not.
  18965. */
  18966. isEnvironmentTexture( texture ) {
  18967. const mapping = texture.mapping;
  18968. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18969. }
  18970. /**
  18971. * Frees internal resource when the given texture isn't
  18972. * required anymore.
  18973. *
  18974. * @param {Texture} texture - The texture to destroy.
  18975. */
  18976. _destroyTexture( texture ) {
  18977. this.backend.destroySampler( texture );
  18978. this.backend.destroyTexture( texture );
  18979. this.delete( texture );
  18980. }
  18981. }
  18982. /**
  18983. * A four-component version of {@link Color} which is internally
  18984. * used by the renderer to represents clear color with alpha as
  18985. * one object.
  18986. *
  18987. * @private
  18988. * @augments Color
  18989. */
  18990. class Color4 extends Color {
  18991. /**
  18992. * Constructs a new four-component color.
  18993. * You can also pass a single THREE.Color, hex or
  18994. * string argument to this constructor.
  18995. *
  18996. * @param {Number|String} [r=1] - The red value.
  18997. * @param {Number} [g=1] - The green value.
  18998. * @param {Number} [b=1] - The blue value.
  18999. * @param {Number} [a=1] - The alpha value.
  19000. */
  19001. constructor( r, g, b, a = 1 ) {
  19002. super( r, g, b );
  19003. this.a = a;
  19004. }
  19005. /**
  19006. * Overwrites the default to honor alpha.
  19007. * You can also pass a single THREE.Color, hex or
  19008. * string argument to this method.
  19009. *
  19010. * @param {Number|String} r - The red value.
  19011. * @param {Number} g - The green value.
  19012. * @param {Number} b - The blue value.
  19013. * @param {Number} [a=1] - The alpha value.
  19014. * @return {Color4} A reference to this object.
  19015. */
  19016. set( r, g, b, a = 1 ) {
  19017. this.a = a;
  19018. return super.set( r, g, b );
  19019. }
  19020. /**
  19021. * Overwrites the default to honor alpha.
  19022. *
  19023. * @param {Color4} color - The color to copy.
  19024. * @return {Color4} A reference to this object.
  19025. */
  19026. copy( color ) {
  19027. if ( color.a !== undefined ) this.a = color.a;
  19028. return super.copy( color );
  19029. }
  19030. /**
  19031. * Overwrites the default to honor alpha.
  19032. *
  19033. * @return {Color4} The cloned color.
  19034. */
  19035. clone() {
  19036. return new this.constructor( this.r, this.g, this.b, this.a );
  19037. }
  19038. }
  19039. /** @module ParameterNode **/
  19040. /**
  19041. * Special version of {@link PropertyNode} which is used for parameters.
  19042. *
  19043. * @augments PropertyNode
  19044. */
  19045. class ParameterNode extends PropertyNode {
  19046. static get type() {
  19047. return 'ParameterNode';
  19048. }
  19049. /**
  19050. * Constructs a new parameter node.
  19051. *
  19052. * @param {String} nodeType - The type of the node.
  19053. * @param {String?} [name=null] - The name of the parameter in the shader.
  19054. */
  19055. constructor( nodeType, name = null ) {
  19056. super( nodeType, name );
  19057. /**
  19058. * This flag can be used for type testing.
  19059. *
  19060. * @type {Boolean}
  19061. * @readonly
  19062. * @default true
  19063. */
  19064. this.isParameterNode = true;
  19065. }
  19066. getHash() {
  19067. return this.uuid;
  19068. }
  19069. generate() {
  19070. return this.name;
  19071. }
  19072. }
  19073. /**
  19074. * TSL function for creating a parameter node.
  19075. *
  19076. * @function
  19077. * @param {String} type - The type of the node.
  19078. * @param {String?} name - The name of the parameter in the shader.
  19079. * @returns {ParameterNode}
  19080. */
  19081. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19082. /** @module StackNode **/
  19083. /**
  19084. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19085. * They are usually needed in cases like `If`, `Else`.
  19086. *
  19087. * @augments Node
  19088. */
  19089. class StackNode extends Node {
  19090. static get type() {
  19091. return 'StackNode';
  19092. }
  19093. /**
  19094. * Constructs a new stack node.
  19095. *
  19096. * @param {StackNode?} [parent=null] - The parent stack node.
  19097. */
  19098. constructor( parent = null ) {
  19099. super();
  19100. /**
  19101. * List of nodes.
  19102. *
  19103. * @type {Array<Node>}
  19104. */
  19105. this.nodes = [];
  19106. /**
  19107. * The output node.
  19108. *
  19109. * @type {Node?}
  19110. * @default null
  19111. */
  19112. this.outputNode = null;
  19113. /**
  19114. * The parent stack node.
  19115. *
  19116. * @type {StackNode}
  19117. * @default null
  19118. */
  19119. this.parent = parent;
  19120. /**
  19121. * The current conditional node.
  19122. *
  19123. * @private
  19124. * @type {ConditionalNode}
  19125. * @default null
  19126. */
  19127. this._currentCond = null;
  19128. /**
  19129. * This flag can be used for type testing.
  19130. *
  19131. * @type {Boolean}
  19132. * @readonly
  19133. * @default true
  19134. */
  19135. this.isStackNode = true;
  19136. }
  19137. getNodeType( builder ) {
  19138. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19139. }
  19140. /**
  19141. * Adds a node to this stack.
  19142. *
  19143. * @param {Node} node - The node to add.
  19144. * @return {StackNode} A reference to this stack node.
  19145. */
  19146. add( node ) {
  19147. this.nodes.push( node );
  19148. return this;
  19149. }
  19150. /**
  19151. * Represent an `if` statement in TSL.
  19152. *
  19153. * @param {Node} boolNode - Represents the condition.
  19154. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19155. * @return {StackNode} A reference to this stack node.
  19156. */
  19157. If( boolNode, method ) {
  19158. const methodNode = new ShaderNode( method );
  19159. this._currentCond = select( boolNode, methodNode );
  19160. return this.add( this._currentCond );
  19161. }
  19162. /**
  19163. * Represent an `elseif` statement in TSL.
  19164. *
  19165. * @param {Node} boolNode - Represents the condition.
  19166. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19167. * @return {StackNode} A reference to this stack node.
  19168. */
  19169. ElseIf( boolNode, method ) {
  19170. const methodNode = new ShaderNode( method );
  19171. const ifNode = select( boolNode, methodNode );
  19172. this._currentCond.elseNode = ifNode;
  19173. this._currentCond = ifNode;
  19174. return this;
  19175. }
  19176. /**
  19177. * Represent an `else` statement in TSL.
  19178. *
  19179. * @param {Function} method - TSL code which is executed in the `else` case.
  19180. * @return {StackNode} A reference to this stack node.
  19181. */
  19182. Else( method ) {
  19183. this._currentCond.elseNode = new ShaderNode( method );
  19184. return this;
  19185. }
  19186. build( builder, ...params ) {
  19187. const previousStack = getCurrentStack();
  19188. setCurrentStack( this );
  19189. for ( const node of this.nodes ) {
  19190. node.build( builder, 'void' );
  19191. }
  19192. setCurrentStack( previousStack );
  19193. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19194. }
  19195. // deprecated
  19196. /**
  19197. * @function
  19198. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19199. *
  19200. * @param {...any} params
  19201. * @returns {StackNode}
  19202. */
  19203. else( ...params ) { // @deprecated, r168
  19204. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19205. return this.Else( ...params );
  19206. }
  19207. /**
  19208. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19209. *
  19210. * @param {...any} params
  19211. * @returns {StackNode}
  19212. */
  19213. elseif( ...params ) { // @deprecated, r168
  19214. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19215. return this.ElseIf( ...params );
  19216. }
  19217. }
  19218. /**
  19219. * TSL function for creating a stack node.
  19220. *
  19221. * @function
  19222. * @param {StackNode?} [parent=null] - The parent stack node.
  19223. * @returns {StackNode}
  19224. */
  19225. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19226. /** @module OutputStructNode **/
  19227. /**
  19228. * This node can be used to define multiple outputs in a shader programs.
  19229. *
  19230. * @augments Node
  19231. */
  19232. class OutputStructNode extends Node {
  19233. static get type() {
  19234. return 'OutputStructNode';
  19235. }
  19236. /**
  19237. * Constructs a new output struct node. The constructor can be invoked with an
  19238. * arbitrary number of nodes representing the members.
  19239. *
  19240. * @param {...Node} members - A parameter list of nodes.
  19241. */
  19242. constructor( ...members ) {
  19243. super();
  19244. /**
  19245. * An array of nodes which defines the output.
  19246. *
  19247. * @type {Array<Node>}
  19248. */
  19249. this.members = members;
  19250. /**
  19251. * This flag can be used for type testing.
  19252. *
  19253. * @type {Boolean}
  19254. * @readonly
  19255. * @default true
  19256. */
  19257. this.isOutputStructNode = true;
  19258. }
  19259. setup( builder ) {
  19260. super.setup( builder );
  19261. const members = this.members;
  19262. const types = [];
  19263. for ( let i = 0; i < members.length; i ++ ) {
  19264. types.push( members[ i ].getNodeType( builder ) );
  19265. }
  19266. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19267. }
  19268. generate( builder, output ) {
  19269. const propertyName = builder.getOutputStructName();
  19270. const members = this.members;
  19271. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19272. for ( let i = 0; i < members.length; i ++ ) {
  19273. const snippet = members[ i ].build( builder, output );
  19274. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19275. }
  19276. return propertyName;
  19277. }
  19278. }
  19279. /**
  19280. * TSL function for creating an output struct node.
  19281. *
  19282. * @function
  19283. * @param {...Node} members - A parameter list of nodes.
  19284. * @returns {OutputStructNode}
  19285. */
  19286. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19287. /** @module MRTNode **/
  19288. /**
  19289. * Returns the MRT texture index for the given name.
  19290. *
  19291. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19292. * @param {String} name - The name of the MRT texture which index is requested.
  19293. * @return {Number} The texture index.
  19294. */
  19295. function getTextureIndex( textures, name ) {
  19296. for ( let i = 0; i < textures.length; i ++ ) {
  19297. if ( textures[ i ].name === name ) {
  19298. return i;
  19299. }
  19300. }
  19301. return - 1;
  19302. }
  19303. /**
  19304. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19305. * post-processing is shown below:
  19306. * ```js
  19307. * const mrtNode = mrt( {
  19308. * output: output,
  19309. * normal: normalView
  19310. * } ) );
  19311. * ```
  19312. * The MRT output is defined as a dictionary.
  19313. *
  19314. * @augments OutputStructNode
  19315. */
  19316. class MRTNode extends OutputStructNode {
  19317. static get type() {
  19318. return 'MRTNode';
  19319. }
  19320. /**
  19321. * Constructs a new output struct node.
  19322. *
  19323. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19324. */
  19325. constructor( outputNodes ) {
  19326. super();
  19327. /**
  19328. * A dictionary representing the MRT outputs. The key
  19329. * is the name of the output, the value the node which produces
  19330. * the output result.
  19331. *
  19332. * @type {Object<String, Node>}
  19333. */
  19334. this.outputNodes = outputNodes;
  19335. /**
  19336. * This flag can be used for type testing.
  19337. *
  19338. * @type {Boolean}
  19339. * @readonly
  19340. * @default true
  19341. */
  19342. this.isMRTNode = true;
  19343. }
  19344. /**
  19345. * Returns `true` if the MRT node has an output with the given name.
  19346. *
  19347. * @param {String} name - The name of the output.
  19348. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19349. */
  19350. has( name ) {
  19351. return this.outputNodes[ name ] !== undefined;
  19352. }
  19353. /**
  19354. * Returns the output node for the given name.
  19355. *
  19356. * @param {String} name - The name of the output.
  19357. * @return {Node} The output node.
  19358. */
  19359. get( name ) {
  19360. return this.outputNodes[ name ];
  19361. }
  19362. /**
  19363. * Merges the outputs of the given MRT node with the outputs of this node.
  19364. *
  19365. * @param {MRTNode} mrtNode - The MRT to merge.
  19366. * @return {MRTNode} A new MRT node with merged outputs..
  19367. */
  19368. merge( mrtNode ) {
  19369. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19370. return mrt( outputs );
  19371. }
  19372. setup( builder ) {
  19373. const outputNodes = this.outputNodes;
  19374. const mrt = builder.renderer.getRenderTarget();
  19375. const members = [];
  19376. const textures = mrt.textures;
  19377. for ( const name in outputNodes ) {
  19378. const index = getTextureIndex( textures, name );
  19379. members[ index ] = vec4( outputNodes[ name ] );
  19380. }
  19381. this.members = members;
  19382. return super.setup( builder );
  19383. }
  19384. }
  19385. /**
  19386. * TSL function for creating a MRT node.
  19387. *
  19388. * @function
  19389. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19390. * @returns {MRTNode}
  19391. */
  19392. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19393. /** @module Hash **/
  19394. /**
  19395. * Generates a hash value in the range `[0, 1]` from the given seed.
  19396. *
  19397. * @method
  19398. * @param {Node<float>} seed - The seed.
  19399. * @return {Node<float>} The hash value.
  19400. */
  19401. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19402. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19403. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19404. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19405. const result = word.shiftRight( 22 ).bitXor( word );
  19406. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19407. } );
  19408. /** @module MathUtils **/
  19409. /**
  19410. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19411. * The corners are mapped to `0` and the center to `1`.
  19412. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19413. *
  19414. * @method
  19415. * @param {Node<float>} x - The value to remap.
  19416. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19417. * @return {Node<float>} The remapped value.
  19418. */
  19419. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19420. /**
  19421. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19422. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  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 - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19428. * @return {Node<float>} The remapped value.
  19429. */
  19430. 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 ) );
  19431. /**
  19432. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19433. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19434. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19435. *
  19436. * @method
  19437. * @param {Node<float>} x - The value to remap.
  19438. * @param {Node<float>} a - First control parameter.
  19439. * @param {Node<float>} b - Second control parameter.
  19440. * @return {Node<float>} The remapped value.
  19441. */
  19442. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19443. /**
  19444. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19445. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19446. *
  19447. * @method
  19448. * @param {Node<float>} x - The value to compute the sin for.
  19449. * @param {Node<float>} k - Controls the amount of bounces.
  19450. * @return {Node<float>} The result value.
  19451. */
  19452. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19453. // https://github.com/cabbibo/glsl-tri-noise-3d
  19454. /** @module TriNoise3D **/
  19455. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19456. return x.fract().sub( .5 ).abs();
  19457. } ).setLayout( {
  19458. name: 'tri',
  19459. type: 'float',
  19460. inputs: [
  19461. { name: 'x', type: 'float' }
  19462. ]
  19463. } );
  19464. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19465. 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. ) ) ) ) );
  19466. } ).setLayout( {
  19467. name: 'tri3',
  19468. type: 'vec3',
  19469. inputs: [
  19470. { name: 'p', type: 'vec3' }
  19471. ]
  19472. } );
  19473. /**
  19474. * Generates a noise value from the given position, speed and time parameters.
  19475. *
  19476. * @method
  19477. * @param {Node<vec3>} position - The position.
  19478. * @param {Node<float>} speed - The speed.
  19479. * @param {Node<float>} time - The time.
  19480. * @return {Node<float>} The generated noise.
  19481. */
  19482. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19483. const p = vec3( position ).toVar();
  19484. const z = float( 1.4 ).toVar();
  19485. const rz = float( 0.0 ).toVar();
  19486. const bp = vec3( p ).toVar();
  19487. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19488. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19489. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19490. bp.mulAssign( 1.8 );
  19491. z.mulAssign( 1.5 );
  19492. p.mulAssign( 1.2 );
  19493. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19494. rz.addAssign( t.div( z ) );
  19495. bp.addAssign( 0.14 );
  19496. } );
  19497. return rz;
  19498. } ).setLayout( {
  19499. name: 'triNoise3D',
  19500. type: 'float',
  19501. inputs: [
  19502. { name: 'position', type: 'vec3' },
  19503. { name: 'speed', type: 'float' },
  19504. { name: 'time', type: 'float' }
  19505. ]
  19506. } );
  19507. /** @module FunctionOverloadingNode **/
  19508. /**
  19509. * This class allows to define multiple overloaded versions
  19510. * of the same function. Depending on the parameters of the function
  19511. * call, the node picks the best-fit overloaded version.
  19512. *
  19513. * @augments Node
  19514. */
  19515. class FunctionOverloadingNode extends Node {
  19516. static get type() {
  19517. return 'FunctionOverloadingNode';
  19518. }
  19519. /**
  19520. * Constructs a new function overloading node.
  19521. *
  19522. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19523. * @param {...Node} parametersNodes - A list of parameter nodes.
  19524. */
  19525. constructor( functionNodes = [], ...parametersNodes ) {
  19526. super();
  19527. /**
  19528. * Array of `Fn` function definitions.
  19529. *
  19530. * @type {Array<Function>}
  19531. */
  19532. this.functionNodes = functionNodes;
  19533. /**
  19534. * A list of parameter nodes.
  19535. *
  19536. * @type {Array<Node>}
  19537. */
  19538. this.parametersNodes = parametersNodes;
  19539. /**
  19540. * The selected overloaded function call.
  19541. *
  19542. * @private
  19543. * @type {ShaderCallNodeInternal}
  19544. */
  19545. this._candidateFnCall = null;
  19546. /**
  19547. * This node is marked as global.
  19548. *
  19549. * @type {Boolean}
  19550. * @default true
  19551. */
  19552. this.global = true;
  19553. }
  19554. /**
  19555. * This method is overwritten since the node type is inferred from
  19556. * the function's return type.
  19557. *
  19558. * @param {NodeBuilder} builder - The current node builder.
  19559. * @return {String} The node type.
  19560. */
  19561. getNodeType() {
  19562. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19563. }
  19564. setup( builder ) {
  19565. const params = this.parametersNodes;
  19566. let candidateFnCall = this._candidateFnCall;
  19567. if ( candidateFnCall === null ) {
  19568. let candidateFn = null;
  19569. let candidateScore = - 1;
  19570. for ( const functionNode of this.functionNodes ) {
  19571. const shaderNode = functionNode.shaderNode;
  19572. const layout = shaderNode.layout;
  19573. if ( layout === null ) {
  19574. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19575. }
  19576. const inputs = layout.inputs;
  19577. if ( params.length === inputs.length ) {
  19578. let score = 0;
  19579. for ( let i = 0; i < params.length; i ++ ) {
  19580. const param = params[ i ];
  19581. const input = inputs[ i ];
  19582. if ( param.getNodeType( builder ) === input.type ) {
  19583. score ++;
  19584. } else {
  19585. score = 0;
  19586. }
  19587. }
  19588. if ( score > candidateScore ) {
  19589. candidateFn = functionNode;
  19590. candidateScore = score;
  19591. }
  19592. }
  19593. }
  19594. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19595. }
  19596. return candidateFnCall;
  19597. }
  19598. }
  19599. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19600. /**
  19601. * TSL function for creating a function overloading node.
  19602. *
  19603. * @function
  19604. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19605. * @returns {FunctionOverloadingNode}
  19606. */
  19607. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19608. /** @module Timer **/
  19609. /**
  19610. * Represents the elapsed time in seconds.
  19611. *
  19612. * @type {UniformNode<float>}
  19613. */
  19614. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19615. /**
  19616. * Represents the delta time in seconds.
  19617. *
  19618. * @type {UniformNode<float>}
  19619. */
  19620. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19621. /**
  19622. * Represents the current frame ID.
  19623. *
  19624. * @type {UniformNode<uint>}
  19625. */
  19626. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19627. // Deprecated
  19628. /**
  19629. * @function
  19630. * @deprecated since r170. Use {@link time} instead.
  19631. *
  19632. * @param {Number} [timeScale=1] - The time scale.
  19633. * @returns {UniformNode<float>}
  19634. */
  19635. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19636. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19637. return time.mul( timeScale );
  19638. };
  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 timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19647. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19648. return time.mul( timeScale );
  19649. };
  19650. /**
  19651. * @function
  19652. * @deprecated since r170. Use {@link deltaTime} instead.
  19653. *
  19654. * @param {Number} [timeScale=1] - The time scale.
  19655. * @returns {UniformNode<float>}
  19656. */
  19657. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19658. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19659. return deltaTime.mul( timeScale );
  19660. };
  19661. /** @module Oscillators **/
  19662. /**
  19663. * Generates a sine wave oscillation based on a timer.
  19664. *
  19665. * @method
  19666. * @param {Node<float>} t - The timer to generate the oscillation with.
  19667. * @return {Node<float>} The oscillation node.
  19668. */
  19669. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19670. /**
  19671. * Generates a square wave oscillation based on a timer.
  19672. *
  19673. * @method
  19674. * @param {Node<float>} t - The timer to generate the oscillation with.
  19675. * @return {Node<float>} The oscillation node.
  19676. */
  19677. const oscSquare = ( t = time ) => t.fract().round();
  19678. /**
  19679. * Generates a triangle wave oscillation based on a timer.
  19680. *
  19681. * @method
  19682. * @param {Node<float>} t - The timer to generate the oscillation with.
  19683. * @return {Node<float>} The oscillation node.
  19684. */
  19685. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19686. /**
  19687. * Generates a sawtooth wave oscillation based on a timer.
  19688. *
  19689. * @method
  19690. * @param {Node<float>} t - The timer to generate the oscillation with.
  19691. * @return {Node<float>} The oscillation node.
  19692. */
  19693. const oscSawtooth = ( t = time ) => t.fract();
  19694. /** @module UVUtils **/
  19695. /**
  19696. * Rotates the given uv coordinates around a center point
  19697. *
  19698. * @method
  19699. * @param {Node<vec2>} uv - The uv coordinates.
  19700. * @param {Node<float>} rotation - The rotation defined in radians.
  19701. * @param {Node<vec2>} center - The center of rotation
  19702. * @return {Node<vec2>} The rotated uv coordinates.
  19703. */
  19704. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19705. return rotate( uv.sub( center ), rotation ).add( center );
  19706. } );
  19707. /**
  19708. * Applies a spherical warping effect to the given uv coordinates.
  19709. *
  19710. * @method
  19711. * @param {Node<vec2>} uv - The uv coordinates.
  19712. * @param {Node<float>} strength - The strength of the effect.
  19713. * @param {Node<vec2>} center - The center point
  19714. * @return {Node<vec2>} The updated uv coordinates.
  19715. */
  19716. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19717. const delta = uv.sub( center );
  19718. const delta2 = delta.dot( delta );
  19719. const delta4 = delta2.mul( delta2 );
  19720. const deltaOffset = delta4.mul( strength );
  19721. return uv.add( delta.mul( deltaOffset ) );
  19722. } );
  19723. /** @module SpriteUtils **/
  19724. /**
  19725. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19726. * oriented always towards the camera.
  19727. *
  19728. * ```js
  19729. * material.vertexNode = billboarding();
  19730. * ```
  19731. *
  19732. * @method
  19733. * @param {Object} config - The configuration object.
  19734. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19735. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19736. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19737. * @return {Node<vec3>} The updated vertex position in clip space.
  19738. */
  19739. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19740. let worldMatrix;
  19741. if ( position !== null ) {
  19742. worldMatrix = modelWorldMatrix.toVar();
  19743. worldMatrix[ 3 ][ 0 ] = position.x;
  19744. worldMatrix[ 3 ][ 1 ] = position.y;
  19745. worldMatrix[ 3 ][ 2 ] = position.z;
  19746. } else {
  19747. worldMatrix = modelWorldMatrix;
  19748. }
  19749. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19750. if ( defined( horizontal ) ) {
  19751. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19752. modelViewMatrix[ 0 ][ 1 ] = 0;
  19753. modelViewMatrix[ 0 ][ 2 ] = 0;
  19754. }
  19755. if ( defined( vertical ) ) {
  19756. modelViewMatrix[ 1 ][ 0 ] = 0;
  19757. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19758. modelViewMatrix[ 1 ][ 2 ] = 0;
  19759. }
  19760. modelViewMatrix[ 2 ][ 0 ] = 0;
  19761. modelViewMatrix[ 2 ][ 1 ] = 0;
  19762. modelViewMatrix[ 2 ][ 2 ] = 1;
  19763. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19764. } );
  19765. /** @module ViewportUtils **/
  19766. /**
  19767. * A special version of a screen uv function that involves a depth comparison
  19768. * when computing the final uvs. The function mitigates visual errors when
  19769. * using viewport texture nodes for refraction purposes. Without this function
  19770. * objects in front of a refractive surface might appear on the refractive surface
  19771. * which is incorrect.
  19772. *
  19773. * @method
  19774. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19775. * @return {Node<vec2>} The update uv coordinates.
  19776. */
  19777. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19778. const depth = linearDepth();
  19779. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19780. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19781. return finalUV;
  19782. } );
  19783. /** @module SpriteSheetUVNode **/
  19784. /**
  19785. * Can be used to compute texture coordinates for animated sprite sheets.
  19786. *
  19787. * ```js
  19788. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19789. *
  19790. * material.colorNode = texture( spriteSheet, uvNode );
  19791. * ```
  19792. *
  19793. * @augments Node
  19794. */
  19795. class SpriteSheetUVNode extends Node {
  19796. static get type() {
  19797. return 'SpriteSheetUVNode';
  19798. }
  19799. /**
  19800. * Constructs a new sprite sheet uv node.
  19801. *
  19802. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19803. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19804. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19805. */
  19806. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19807. super( 'vec2' );
  19808. /**
  19809. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19810. *
  19811. * @type {Node<vec2>}
  19812. */
  19813. this.countNode = countNode;
  19814. /**
  19815. * The uv node.
  19816. *
  19817. * @type {Node<vec2>}
  19818. */
  19819. this.uvNode = uvNode;
  19820. /**
  19821. * The node that defines the current frame/sprite.
  19822. *
  19823. * @type {Node<float>}
  19824. */
  19825. this.frameNode = frameNode;
  19826. }
  19827. setup() {
  19828. const { frameNode, uvNode, countNode } = this;
  19829. const { width, height } = countNode;
  19830. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19831. const column = frameNum.mod( width );
  19832. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19833. const scale = countNode.reciprocal();
  19834. const uvFrameOffset = vec2( column, row );
  19835. return uvNode.add( uvFrameOffset ).mul( scale );
  19836. }
  19837. }
  19838. /**
  19839. * TSL function for creating a sprite sheet uv node.
  19840. *
  19841. * @function
  19842. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19843. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19844. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19845. * @returns {SpriteSheetUVNode}
  19846. */
  19847. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19848. /** @module TriplanarTexturesNode **/
  19849. /**
  19850. * Can be used for triplanar texture mapping.
  19851. *
  19852. * ```js
  19853. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19854. * ```
  19855. *
  19856. * @augments Node
  19857. */
  19858. class TriplanarTexturesNode extends Node {
  19859. static get type() {
  19860. return 'TriplanarTexturesNode';
  19861. }
  19862. /**
  19863. * Constructs a new triplanar textures node.
  19864. *
  19865. * @param {Node} textureXNode - First texture node.
  19866. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19867. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19868. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19869. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19870. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19871. */
  19872. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19873. super( 'vec4' );
  19874. /**
  19875. * First texture node.
  19876. *
  19877. * @type {Node}
  19878. */
  19879. this.textureXNode = textureXNode;
  19880. /**
  19881. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19882. *
  19883. * @type {Node}
  19884. * @default null
  19885. */
  19886. this.textureYNode = textureYNode;
  19887. /**
  19888. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19889. *
  19890. * @type {Node}
  19891. * @default null
  19892. */
  19893. this.textureZNode = textureZNode;
  19894. /**
  19895. * The scale node.
  19896. *
  19897. * @type {Node<float>}
  19898. * @default float(1)
  19899. */
  19900. this.scaleNode = scaleNode;
  19901. /**
  19902. * Vertex positions in local space.
  19903. *
  19904. * @type {Node<vec3>}
  19905. * @default positionLocal
  19906. */
  19907. this.positionNode = positionNode;
  19908. /**
  19909. * Normals in local space.
  19910. *
  19911. * @type {Node<vec3>}
  19912. * @default normalLocal
  19913. */
  19914. this.normalNode = normalNode;
  19915. }
  19916. setup() {
  19917. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19918. // Ref: https://github.com/keijiro/StandardTriplanar
  19919. // Blending factor of triplanar mapping
  19920. let bf = normalNode.abs().normalize();
  19921. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19922. // Triplanar mapping
  19923. const tx = positionNode.yz.mul( scaleNode );
  19924. const ty = positionNode.zx.mul( scaleNode );
  19925. const tz = positionNode.xy.mul( scaleNode );
  19926. // Base color
  19927. const textureX = textureXNode.value;
  19928. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19929. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19930. const cx = texture( textureX, tx ).mul( bf.x );
  19931. const cy = texture( textureY, ty ).mul( bf.y );
  19932. const cz = texture( textureZ, tz ).mul( bf.z );
  19933. return add( cx, cy, cz );
  19934. }
  19935. }
  19936. /**
  19937. * TSL function for creating a triplanar textures node.
  19938. *
  19939. * @function
  19940. * @param {Node} textureXNode - First texture node.
  19941. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19942. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19943. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19944. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19945. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19946. * @returns {TriplanarTexturesNode}
  19947. */
  19948. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19949. /**
  19950. * TSL function for creating a triplanar textures node.
  19951. *
  19952. * @function
  19953. * @param {Node} textureXNode - First texture node.
  19954. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19955. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19956. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19957. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19958. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19959. * @returns {TriplanarTexturesNode}
  19960. */
  19961. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19962. /** @module ReflectorNode **/
  19963. const _reflectorPlane = new Plane();
  19964. const _normal = new Vector3();
  19965. const _reflectorWorldPosition = new Vector3();
  19966. const _cameraWorldPosition = new Vector3();
  19967. const _rotationMatrix = new Matrix4();
  19968. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19969. const clipPlane = new Vector4();
  19970. const _view = new Vector3();
  19971. const _target = new Vector3();
  19972. const _q = new Vector4();
  19973. const _size$2 = new Vector2();
  19974. const _defaultRT = new RenderTarget();
  19975. const _defaultUV = screenUV.flipX();
  19976. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19977. let _inReflector = false;
  19978. /**
  19979. * This node can be used to implement mirror-like flat reflective surfaces.
  19980. *
  19981. * ```js
  19982. * const groundReflector = reflector();
  19983. * material.colorNode = groundReflector;
  19984. *
  19985. * const plane = new Mesh( geometry, material );
  19986. * plane.add( groundReflector.target );
  19987. * ```
  19988. *
  19989. * @augments module:TextureNode~TextureNode
  19990. */
  19991. class ReflectorNode extends TextureNode {
  19992. static get type() {
  19993. return 'ReflectorNode';
  19994. }
  19995. /**
  19996. * Constructs a new reflector node.
  19997. *
  19998. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19999. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20000. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20001. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20002. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20003. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20004. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20005. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20006. */
  20007. constructor( parameters = {} ) {
  20008. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20009. /**
  20010. * A reference to the internal reflector base node which holds the actual implementation.
  20011. *
  20012. * @private
  20013. * @type {ReflectorBaseNode?}
  20014. * @default null
  20015. */
  20016. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20017. /**
  20018. * A reference to the internal depth node.
  20019. *
  20020. * @private
  20021. * @type {Node?}
  20022. * @default null
  20023. */
  20024. this._depthNode = null;
  20025. this.setUpdateMatrix( false );
  20026. }
  20027. /**
  20028. * A reference to the internal reflector node.
  20029. *
  20030. * @type {ReflectorBaseNode}
  20031. */
  20032. get reflector() {
  20033. return this._reflectorBaseNode;
  20034. }
  20035. /**
  20036. * A reference to 3D object the reflector is linked to.
  20037. *
  20038. * @type {Object3D}
  20039. */
  20040. get target() {
  20041. return this._reflectorBaseNode.target;
  20042. }
  20043. /**
  20044. * Returns a node representing the mirror's depth. That can be used
  20045. * to implement more advanced reflection effects like distance attenuation.
  20046. *
  20047. * @return {Node} The depth node.
  20048. */
  20049. getDepthNode() {
  20050. if ( this._depthNode === null ) {
  20051. if ( this._reflectorBaseNode.depth !== true ) {
  20052. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20053. }
  20054. this._depthNode = nodeObject( new ReflectorNode( {
  20055. defaultTexture: _defaultRT.depthTexture,
  20056. reflector: this._reflectorBaseNode
  20057. } ) );
  20058. }
  20059. return this._depthNode;
  20060. }
  20061. setup( builder ) {
  20062. // ignore if used in post-processing
  20063. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20064. return super.setup( builder );
  20065. }
  20066. clone() {
  20067. const texture = new this.constructor( this.reflectorNode );
  20068. texture._reflectorBaseNode = this._reflectorBaseNode;
  20069. return texture;
  20070. }
  20071. }
  20072. /**
  20073. * Holds the actual implementation of the reflector.
  20074. *
  20075. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20076. * in `ReflectorNode`, see #29619.
  20077. *
  20078. * @private
  20079. * @augments Node
  20080. */
  20081. class ReflectorBaseNode extends Node {
  20082. static get type() {
  20083. return 'ReflectorBaseNode';
  20084. }
  20085. /**
  20086. * Constructs a new reflector base node.
  20087. *
  20088. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20089. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20090. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20091. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20092. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20093. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20094. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20095. */
  20096. constructor( textureNode, parameters = {} ) {
  20097. super();
  20098. const {
  20099. target = new Object3D(),
  20100. resolution = 1,
  20101. generateMipmaps = false,
  20102. bounces = true,
  20103. depth = false
  20104. } = parameters;
  20105. /**
  20106. * Represents the rendered reflections as a texture node.
  20107. *
  20108. * @type {TextureNode}
  20109. */
  20110. this.textureNode = textureNode;
  20111. /**
  20112. * The 3D object the reflector is linked to.
  20113. *
  20114. * @type {Object3D}
  20115. * @default {new Object3D()}
  20116. */
  20117. this.target = target;
  20118. /**
  20119. * The resolution scale.
  20120. *
  20121. * @type {Number}
  20122. * @default {1}
  20123. */
  20124. this.resolution = resolution;
  20125. /**
  20126. * Whether mipmaps should be generated or not.
  20127. *
  20128. * @type {Boolean}
  20129. * @default {false}
  20130. */
  20131. this.generateMipmaps = generateMipmaps;
  20132. /**
  20133. * Whether reflectors can render other reflector nodes or not.
  20134. *
  20135. * @type {Boolean}
  20136. * @default {true}
  20137. */
  20138. this.bounces = bounces;
  20139. /**
  20140. * Whether depth data should be generated or not.
  20141. *
  20142. * @type {Boolean}
  20143. * @default {false}
  20144. */
  20145. this.depth = depth;
  20146. /**
  20147. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20148. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20149. *
  20150. * @type {String}
  20151. * @default 'render'
  20152. */
  20153. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20154. /**
  20155. * Weak map for managing virtual cameras.
  20156. *
  20157. * @type {WeakMap<Camera, Camera>}
  20158. */
  20159. this.virtualCameras = new WeakMap();
  20160. /**
  20161. * Weak map for managing render targets.
  20162. *
  20163. * @type {WeakMap<Camera, RenderTarget>}
  20164. */
  20165. this.renderTargets = new WeakMap();
  20166. }
  20167. /**
  20168. * Updates the resolution of the internal render target.
  20169. *
  20170. * @private
  20171. * @param {RenderTarget} renderTarget - The render target to resize.
  20172. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20173. */
  20174. _updateResolution( renderTarget, renderer ) {
  20175. const resolution = this.resolution;
  20176. renderer.getDrawingBufferSize( _size$2 );
  20177. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20178. }
  20179. setup( builder ) {
  20180. this._updateResolution( _defaultRT, builder.renderer );
  20181. return super.setup( builder );
  20182. }
  20183. /**
  20184. * Returns a virtual camera for the given camera. The virtual camera is used to
  20185. * render the scene from the reflector's view so correct reflections can be produced.
  20186. *
  20187. * @param {Camera} camera - The scene's camera.
  20188. * @return {Camera} The corresponding virtual camera.
  20189. */
  20190. getVirtualCamera( camera ) {
  20191. let virtualCamera = this.virtualCameras.get( camera );
  20192. if ( virtualCamera === undefined ) {
  20193. virtualCamera = camera.clone();
  20194. this.virtualCameras.set( camera, virtualCamera );
  20195. }
  20196. return virtualCamera;
  20197. }
  20198. /**
  20199. * Returns a render target for the given camera. The reflections are rendered
  20200. * into this render target.
  20201. *
  20202. * @param {Camera} camera - The scene's camera.
  20203. * @return {RenderTarget} The render target.
  20204. */
  20205. getRenderTarget( camera ) {
  20206. let renderTarget = this.renderTargets.get( camera );
  20207. if ( renderTarget === undefined ) {
  20208. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20209. if ( this.generateMipmaps === true ) {
  20210. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20211. renderTarget.texture.generateMipmaps = true;
  20212. }
  20213. if ( this.depth === true ) {
  20214. renderTarget.depthTexture = new DepthTexture();
  20215. }
  20216. this.renderTargets.set( camera, renderTarget );
  20217. }
  20218. return renderTarget;
  20219. }
  20220. updateBefore( frame ) {
  20221. if ( this.bounces === false && _inReflector ) return false;
  20222. _inReflector = true;
  20223. const { scene, camera, renderer, material } = frame;
  20224. const { target } = this;
  20225. const virtualCamera = this.getVirtualCamera( camera );
  20226. const renderTarget = this.getRenderTarget( virtualCamera );
  20227. renderer.getDrawingBufferSize( _size$2 );
  20228. this._updateResolution( renderTarget, renderer );
  20229. //
  20230. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20231. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20232. _rotationMatrix.extractRotation( target.matrixWorld );
  20233. _normal.set( 0, 0, 1 );
  20234. _normal.applyMatrix4( _rotationMatrix );
  20235. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20236. // Avoid rendering when reflector is facing away
  20237. if ( _view.dot( _normal ) > 0 ) return;
  20238. _view.reflect( _normal ).negate();
  20239. _view.add( _reflectorWorldPosition );
  20240. _rotationMatrix.extractRotation( camera.matrixWorld );
  20241. _lookAtPosition.set( 0, 0, - 1 );
  20242. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20243. _lookAtPosition.add( _cameraWorldPosition );
  20244. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20245. _target.reflect( _normal ).negate();
  20246. _target.add( _reflectorWorldPosition );
  20247. //
  20248. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20249. virtualCamera.position.copy( _view );
  20250. virtualCamera.up.set( 0, 1, 0 );
  20251. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20252. virtualCamera.up.reflect( _normal );
  20253. virtualCamera.lookAt( _target );
  20254. virtualCamera.near = camera.near;
  20255. virtualCamera.far = camera.far;
  20256. virtualCamera.updateMatrixWorld();
  20257. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20258. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20259. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20260. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20261. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20262. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20263. const projectionMatrix = virtualCamera.projectionMatrix;
  20264. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20265. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20266. _q.z = - 1.0;
  20267. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20268. // Calculate the scaled plane vector
  20269. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20270. const clipBias = 0;
  20271. // Replacing the third row of the projection matrix
  20272. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20273. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20274. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20275. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20276. //
  20277. this.textureNode.value = renderTarget.texture;
  20278. if ( this.depth === true ) {
  20279. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20280. }
  20281. material.visible = false;
  20282. const currentRenderTarget = renderer.getRenderTarget();
  20283. const currentMRT = renderer.getMRT();
  20284. const currentAutoClear = renderer.autoClear;
  20285. renderer.setMRT( null );
  20286. renderer.setRenderTarget( renderTarget );
  20287. renderer.autoClear = true;
  20288. renderer.render( scene, virtualCamera );
  20289. renderer.setMRT( currentMRT );
  20290. renderer.setRenderTarget( currentRenderTarget );
  20291. renderer.autoClear = currentAutoClear;
  20292. material.visible = true;
  20293. _inReflector = false;
  20294. }
  20295. }
  20296. /**
  20297. * TSL function for creating a reflector node.
  20298. *
  20299. * @function
  20300. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20301. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20302. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20303. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20304. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20305. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20306. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20307. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20308. * @returns {ReflectorNode}
  20309. */
  20310. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20311. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20312. /**
  20313. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20314. *
  20315. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20316. *
  20317. * @private
  20318. * @augments BufferGeometry
  20319. */
  20320. class QuadGeometry extends BufferGeometry {
  20321. /**
  20322. * Constructs a new quad geometry.
  20323. *
  20324. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20325. */
  20326. constructor( flipY = false ) {
  20327. super();
  20328. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20329. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20330. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20331. }
  20332. }
  20333. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20334. /**
  20335. * This module is a helper for passes which need to render a full
  20336. * screen effect which is quite common in context of post processing.
  20337. *
  20338. * The intended usage is to reuse a single quad mesh for rendering
  20339. * subsequent passes by just reassigning the `material` reference.
  20340. *
  20341. * @augments Mesh
  20342. */
  20343. class QuadMesh extends Mesh {
  20344. /**
  20345. * Constructs a new quad mesh.
  20346. *
  20347. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20348. */
  20349. constructor( material = null ) {
  20350. super( _geometry, material );
  20351. /**
  20352. * The camera to render the quad mesh with.
  20353. *
  20354. * @type {OrthographicCamera}
  20355. * @readonly
  20356. */
  20357. this.camera = _camera;
  20358. /**
  20359. * This flag can be used for type testing.
  20360. *
  20361. * @type {Boolean}
  20362. * @readonly
  20363. * @default true
  20364. */
  20365. this.isQuadMesh = true;
  20366. }
  20367. /**
  20368. * Async version of `render()`.
  20369. *
  20370. * @async
  20371. * @param {Renderer} renderer - The renderer.
  20372. * @return {Promise} A Promise that resolves when the render has been finished.
  20373. */
  20374. async renderAsync( renderer ) {
  20375. return renderer.renderAsync( this, _camera );
  20376. }
  20377. /**
  20378. * Renders the quad mesh
  20379. *
  20380. * @param {Renderer} renderer - The renderer.
  20381. */
  20382. render( renderer ) {
  20383. renderer.render( this, _camera );
  20384. }
  20385. }
  20386. /** @module RTTNode **/
  20387. const _size$1 = /*@__PURE__*/ new Vector2();
  20388. /**
  20389. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20390. * This module is especially relevant in context of post processing where certain nodes require
  20391. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20392. * on this module, the node system can automatically ensure texture input if required.
  20393. *
  20394. * @augments module:TextureNode~TextureNode
  20395. */
  20396. class RTTNode extends TextureNode {
  20397. static get type() {
  20398. return 'RTTNode';
  20399. }
  20400. /**
  20401. * Constructs a new RTT node.
  20402. *
  20403. * @param {Node} node - The node to render a texture with.
  20404. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20405. * @param {Number?} [height=null] - The height of the internal render target.
  20406. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20407. */
  20408. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20409. const renderTarget = new RenderTarget( width, height, options );
  20410. super( renderTarget.texture, uv() );
  20411. /**
  20412. * The node to render a texture with.
  20413. *
  20414. * @type {Node}
  20415. */
  20416. this.node = node;
  20417. /**
  20418. * The width of the internal render target.
  20419. * If not width is applied, the render target is automatically resized.
  20420. *
  20421. * @type {Number?}
  20422. * @default null
  20423. */
  20424. this.width = width;
  20425. /**
  20426. * The height of the internal render target.
  20427. *
  20428. * @type {Number?}
  20429. * @default null
  20430. */
  20431. this.height = height;
  20432. /**
  20433. * The pixel ratio
  20434. *
  20435. * @type {Number}
  20436. * @default 1
  20437. */
  20438. this.pixelRatio = 1;
  20439. /**
  20440. * The render target
  20441. *
  20442. * @type {RenderTarget}
  20443. */
  20444. this.renderTarget = renderTarget;
  20445. /**
  20446. * Whether the texture requires an update or not.
  20447. *
  20448. * @type {Boolean}
  20449. * @default true
  20450. */
  20451. this.textureNeedsUpdate = true;
  20452. /**
  20453. * Whether the texture should automatically be updated or not.
  20454. *
  20455. * @type {Boolean}
  20456. * @default true
  20457. */
  20458. this.autoUpdate = true;
  20459. /**
  20460. * The node which is used with the quad mesh for RTT.
  20461. *
  20462. * @private
  20463. * @type {Node}
  20464. * @default null
  20465. */
  20466. this._rttNode = null;
  20467. /**
  20468. * The internal quad mesh for RTT.
  20469. *
  20470. * @private
  20471. * @type {QuadMesh}
  20472. */
  20473. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20474. /**
  20475. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20476. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20477. *
  20478. * @type {String}
  20479. * @default 'render'
  20480. */
  20481. this.updateBeforeType = NodeUpdateType.RENDER;
  20482. }
  20483. /**
  20484. * Whether the internal render target should automatically be resized or not.
  20485. *
  20486. * @type {Boolean}
  20487. * @readonly
  20488. * @default true
  20489. */
  20490. get autoSize() {
  20491. return this.width === null;
  20492. }
  20493. setup( builder ) {
  20494. this._rttNode = this.node.context( builder.getSharedContext() );
  20495. this._quadMesh.material.name = 'RTT';
  20496. this._quadMesh.material.needsUpdate = true;
  20497. return super.setup( builder );
  20498. }
  20499. /**
  20500. * Sets the size of the internal render target
  20501. *
  20502. * @param {Number} width - The width to set.
  20503. * @param {Number} height - The width to set.
  20504. */
  20505. setSize( width, height ) {
  20506. this.width = width;
  20507. this.height = height;
  20508. const effectiveWidth = width * this.pixelRatio;
  20509. const effectiveHeight = height * this.pixelRatio;
  20510. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20511. this.textureNeedsUpdate = true;
  20512. }
  20513. /**
  20514. * Sets the pixel ratio. This will also resize the render target.
  20515. *
  20516. * @param {Number} pixelRatio - The pixel ratio to set.
  20517. */
  20518. setPixelRatio( pixelRatio ) {
  20519. this.pixelRatio = pixelRatio;
  20520. this.setSize( this.width, this.height );
  20521. }
  20522. updateBefore( { renderer } ) {
  20523. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20524. this.textureNeedsUpdate = false;
  20525. //
  20526. if ( this.autoSize === true ) {
  20527. this.pixelRatio = renderer.getPixelRatio();
  20528. const size = renderer.getSize( _size$1 );
  20529. this.setSize( size.width, size.height );
  20530. }
  20531. //
  20532. this._quadMesh.material.fragmentNode = this._rttNode;
  20533. //
  20534. const currentRenderTarget = renderer.getRenderTarget();
  20535. renderer.setRenderTarget( this.renderTarget );
  20536. this._quadMesh.render( renderer );
  20537. renderer.setRenderTarget( currentRenderTarget );
  20538. }
  20539. clone() {
  20540. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20541. newNode.sampler = this.sampler;
  20542. newNode.referenceNode = this;
  20543. return newNode;
  20544. }
  20545. }
  20546. /**
  20547. * TSL function for creating a RTT node.
  20548. *
  20549. * @function
  20550. * @param {Node} node - The node to render a texture with.
  20551. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20552. * @param {Number?} [height=null] - The height of the internal render target.
  20553. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20554. * @returns {RTTNode}
  20555. */
  20556. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20557. /**
  20558. * TSL function for converting nodes to textures nodes.
  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 convertToTexture = ( node, ...params ) => {
  20568. if ( node.isTextureNode ) return node;
  20569. if ( node.isPassNode ) return node.getTextureNode();
  20570. return rtt( node, ...params );
  20571. };
  20572. /** @module PostProcessingUtils **/
  20573. /**
  20574. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20575. * depth value and the camera's inverse projection matrix.
  20576. *
  20577. * @method
  20578. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20579. * @param {Node<float>} depth - The fragment's depth value.
  20580. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20581. * @return {Node<vec3>} The fragments position in view space.
  20582. */
  20583. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20584. let clipSpacePosition;
  20585. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20586. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20587. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20588. } else {
  20589. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20590. }
  20591. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20592. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20593. } );
  20594. /**
  20595. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20596. * and the camera's projection matrix
  20597. *
  20598. * @method
  20599. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20600. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20601. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20602. */
  20603. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20604. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20605. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20606. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20607. } );
  20608. /**
  20609. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20610. * target is available or if flat surface normals are required.
  20611. *
  20612. * @method
  20613. * @param {Node<vec2>} uv - The texture coordinate.
  20614. * @param {DepthTexture} depthTexture - The depth texture.
  20615. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20616. * @return {Node<vec3>} The computed normal vector.
  20617. */
  20618. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20619. const size = textureSize( textureLoad( depthTexture ) );
  20620. const p = ivec2( uv.mul( size ) ).toVar();
  20621. const c0 = textureLoad( depthTexture, p ).toVar();
  20622. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20623. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20624. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20625. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20626. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20627. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20628. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20629. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20630. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20631. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20632. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20633. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20634. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20635. 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 ) ) );
  20636. 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 ) ) );
  20637. return normalize( cross( dpdx, dpdy ) );
  20638. } );
  20639. /**
  20640. * This special type of instanced buffer attribute is intended for compute shaders.
  20641. * In earlier three.js versions it was only possible to update attribute data
  20642. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20643. * new material system and renderer it is now possible to use compute shaders
  20644. * to compute the data for an attribute more efficiently on the GPU.
  20645. *
  20646. * The idea is to create an instance of this class and provide it as an input
  20647. * to {@link module:StorageBufferNode}.
  20648. *
  20649. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20650. *
  20651. * @augments InstancedBufferAttribute
  20652. */
  20653. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20654. /**
  20655. * Constructs a new storage instanced buffer attribute.
  20656. *
  20657. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20658. * The subsequent parameters are then obsolete.
  20659. * @param {Number} itemSize - The item size.
  20660. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20661. */
  20662. constructor( count, itemSize, typeClass = Float32Array ) {
  20663. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20664. super( array, itemSize );
  20665. /**
  20666. * This flag can be used for type testing.
  20667. *
  20668. * @type {Boolean}
  20669. * @readonly
  20670. * @default true
  20671. */
  20672. this.isStorageInstancedBufferAttribute = true;
  20673. }
  20674. }
  20675. /**
  20676. * This special type of buffer attribute is intended for compute shaders.
  20677. * In earlier three.js versions it was only possible to update attribute data
  20678. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20679. * new material system and renderer it is now possible to use compute shaders
  20680. * to compute the data for an attribute more efficiently on the GPU.
  20681. *
  20682. * The idea is to create an instance of this class and provide it as an input
  20683. * to {@link module:StorageBufferNode}.
  20684. *
  20685. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20686. *
  20687. * @augments BufferAttribute
  20688. */
  20689. class StorageBufferAttribute extends BufferAttribute {
  20690. /**
  20691. * Constructs a new storage buffer attribute.
  20692. *
  20693. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20694. * The subsequent parameters are then obsolete.
  20695. * @param {Number} itemSize - The item size.
  20696. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20697. */
  20698. constructor( count, itemSize, typeClass = Float32Array ) {
  20699. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20700. super( array, itemSize );
  20701. /**
  20702. * This flag can be used for type testing.
  20703. *
  20704. * @type {Boolean}
  20705. * @readonly
  20706. * @default true
  20707. */
  20708. this.isStorageBufferAttribute = true;
  20709. }
  20710. }
  20711. /** @module StorageArrayElementNode **/
  20712. /**
  20713. * This class enables element access on instances of {@link StorageBufferNode}.
  20714. * In most cases, it is indirectly used when accessing elements with the
  20715. * {@link StorageBufferNode#element} method.
  20716. *
  20717. * ```js
  20718. * const position = positionStorage.element( instanceIndex );
  20719. * ```
  20720. *
  20721. * @augments ArrayElementNode
  20722. */
  20723. class StorageArrayElementNode extends ArrayElementNode {
  20724. static get type() {
  20725. return 'StorageArrayElementNode';
  20726. }
  20727. /**
  20728. * Constructs storage buffer element node.
  20729. *
  20730. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20731. * @param {Node} indexNode - The index node that defines the element access.
  20732. */
  20733. constructor( storageBufferNode, indexNode ) {
  20734. super( storageBufferNode, indexNode );
  20735. /**
  20736. * This flag can be used for type testing.
  20737. *
  20738. * @type {Boolean}
  20739. * @readonly
  20740. * @default true
  20741. */
  20742. this.isStorageArrayElementNode = true;
  20743. }
  20744. /**
  20745. * The storage buffer node.
  20746. *
  20747. * @param {Node} value
  20748. * @type {StorageBufferNode}
  20749. */
  20750. set storageBufferNode( value ) {
  20751. this.node = value;
  20752. }
  20753. get storageBufferNode() {
  20754. return this.node;
  20755. }
  20756. setup( builder ) {
  20757. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20758. if ( this.node.isPBO === true ) {
  20759. builder.setupPBO( this.node );
  20760. }
  20761. }
  20762. return super.setup( builder );
  20763. }
  20764. generate( builder, output ) {
  20765. let snippet;
  20766. const isAssignContext = builder.context.assign;
  20767. //
  20768. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20769. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20770. snippet = builder.generatePBO( this );
  20771. } else {
  20772. snippet = this.node.build( builder );
  20773. }
  20774. } else {
  20775. snippet = super.generate( builder );
  20776. }
  20777. if ( isAssignContext !== true ) {
  20778. const type = this.getNodeType( builder );
  20779. snippet = builder.format( snippet, type, output );
  20780. }
  20781. return snippet;
  20782. }
  20783. }
  20784. /**
  20785. * TSL function for creating a storage element node.
  20786. *
  20787. * @function
  20788. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20789. * @param {Node} indexNode - The index node that defines the element access.
  20790. * @returns {StorageArrayElementNode}
  20791. */
  20792. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20793. /** @module StorageBufferNode **/
  20794. /**
  20795. * This node is used in context of compute shaders and allows to define a
  20796. * storage buffer for data. A typical workflow is to create instances of
  20797. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20798. * setup up a compute shader that writes into the buffers and then convert
  20799. * the storage buffers to attribute nodes for rendering.
  20800. *
  20801. * ```js
  20802. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20803. *
  20804. * const computeInit = Fn( () => { // the compute shader
  20805. *
  20806. * const position = positionBuffer.element( instanceIndex );
  20807. *
  20808. * // compute position data
  20809. *
  20810. * position.x = 1;
  20811. * position.y = 1;
  20812. * position.z = 1;
  20813. *
  20814. * } )().compute( particleCount );
  20815. *
  20816. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20817. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20818. *
  20819. * renderer.computeAsync( computeInit );
  20820. *
  20821. * ```
  20822. *
  20823. * @augments BufferNode
  20824. */
  20825. class StorageBufferNode extends BufferNode {
  20826. static get type() {
  20827. return 'StorageBufferNode';
  20828. }
  20829. /**
  20830. * Constructs a new storage buffer node.
  20831. *
  20832. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20833. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20834. * @param {Number} [bufferCount=0] - The buffer count.
  20835. */
  20836. constructor( value, bufferType = null, bufferCount = 0 ) {
  20837. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20838. bufferType = getTypeFromLength( value.itemSize );
  20839. bufferCount = value.count;
  20840. }
  20841. super( value, bufferType, bufferCount );
  20842. /**
  20843. * This flag can be used for type testing.
  20844. *
  20845. * @type {Boolean}
  20846. * @readonly
  20847. * @default true
  20848. */
  20849. this.isStorageBufferNode = true;
  20850. /**
  20851. * The access type of the texture node.
  20852. *
  20853. * @type {String}
  20854. * @default 'readWrite'
  20855. */
  20856. this.access = NodeAccess.READ_WRITE;
  20857. /**
  20858. * Whether the node is atomic or not.
  20859. *
  20860. * @type {Boolean}
  20861. * @default false
  20862. */
  20863. this.isAtomic = false;
  20864. /**
  20865. * Whether the node represents a PBO or not.
  20866. * Only relevant for WebGL.
  20867. *
  20868. * @type {Boolean}
  20869. * @default false
  20870. */
  20871. this.isPBO = false;
  20872. /**
  20873. * A reference to the internal buffer attribute node.
  20874. *
  20875. * @type {BufferAttributeNode?}
  20876. * @default null
  20877. */
  20878. this._attribute = null;
  20879. /**
  20880. * A reference to the internal varying node.
  20881. *
  20882. * @type {VaryingNode?}
  20883. * @default null
  20884. */
  20885. this._varying = null;
  20886. /**
  20887. * `StorageBufferNode` sets this property to `true` by default.
  20888. *
  20889. * @type {Boolean}
  20890. * @default true
  20891. */
  20892. this.global = true;
  20893. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20894. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20895. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20896. else value.isStorageBufferAttribute = true;
  20897. }
  20898. }
  20899. /**
  20900. * This method is overwritten since the buffer data might be shared
  20901. * and thus the hash should be shared as well.
  20902. *
  20903. * @param {NodeBuilder} builder - The current node builder.
  20904. * @return {String} The hash.
  20905. */
  20906. getHash( builder ) {
  20907. if ( this.bufferCount === 0 ) {
  20908. let bufferData = builder.globalCache.getData( this.value );
  20909. if ( bufferData === undefined ) {
  20910. bufferData = {
  20911. node: this
  20912. };
  20913. builder.globalCache.setData( this.value, bufferData );
  20914. }
  20915. return bufferData.node.uuid;
  20916. }
  20917. return this.uuid;
  20918. }
  20919. /**
  20920. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20921. *
  20922. * @param {NodeBuilder} builder - The current node builder.
  20923. * @return {String} The input type.
  20924. */
  20925. getInputType( /*builder*/ ) {
  20926. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20927. }
  20928. /**
  20929. * Enables element access with the given index node.
  20930. *
  20931. * @param {IndexNode} indexNode - The index node.
  20932. * @return {StorageArrayElementNode} A node representing the element access.
  20933. */
  20934. element( indexNode ) {
  20935. return storageElement( this, indexNode );
  20936. }
  20937. /**
  20938. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20939. *
  20940. * @param {Boolean} value - The value so set.
  20941. * @return {StorageBufferNode} A reference to this node.
  20942. */
  20943. setPBO( value ) {
  20944. this.isPBO = value;
  20945. return this;
  20946. }
  20947. /**
  20948. * Returns the `isPBO` value.
  20949. *
  20950. * @return {Boolean} Whether the node represents a PBO or not.
  20951. */
  20952. getPBO() {
  20953. return this.isPBO;
  20954. }
  20955. /**
  20956. * Defines the node access.
  20957. *
  20958. * @param {String} value - The node access.
  20959. * @return {StorageBufferNode} A reference to this node.
  20960. */
  20961. setAccess( value ) {
  20962. this.access = value;
  20963. return this;
  20964. }
  20965. /**
  20966. * Convenience method for configuring a read-only node access.
  20967. *
  20968. * @return {StorageBufferNode} A reference to this node.
  20969. */
  20970. toReadOnly() {
  20971. return this.setAccess( NodeAccess.READ_ONLY );
  20972. }
  20973. /**
  20974. * Defines whether the node is atomic or not.
  20975. *
  20976. * @param {Boolean} value - The atomic flag.
  20977. * @return {StorageBufferNode} A reference to this node.
  20978. */
  20979. setAtomic( value ) {
  20980. this.isAtomic = value;
  20981. return this;
  20982. }
  20983. /**
  20984. * Convenience method for making this node atomic.
  20985. *
  20986. * @return {StorageBufferNode} A reference to this node.
  20987. */
  20988. toAtomic() {
  20989. return this.setAtomic( true );
  20990. }
  20991. /**
  20992. * Returns attribute data for this storage buffer node.
  20993. *
  20994. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20995. */
  20996. getAttributeData() {
  20997. if ( this._attribute === null ) {
  20998. this._attribute = bufferAttribute( this.value );
  20999. this._varying = varying( this._attribute );
  21000. }
  21001. return {
  21002. attribute: this._attribute,
  21003. varying: this._varying
  21004. };
  21005. }
  21006. /**
  21007. * This method is overwritten since the node type from the availability of storage buffers
  21008. * and the attribute data.
  21009. *
  21010. * @param {NodeBuilder} builder - The current node builder.
  21011. * @return {String} The node type.
  21012. */
  21013. getNodeType( builder ) {
  21014. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21015. return super.getNodeType( builder );
  21016. }
  21017. const { attribute } = this.getAttributeData();
  21018. return attribute.getNodeType( builder );
  21019. }
  21020. /**
  21021. * Generates the code snippet of the storage buffer node.
  21022. *
  21023. * @param {NodeBuilder} builder - The current node builder.
  21024. * @return {String} The generated code snippet.
  21025. */
  21026. generate( builder ) {
  21027. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21028. return super.generate( builder );
  21029. }
  21030. const { attribute, varying } = this.getAttributeData();
  21031. const output = varying.build( builder );
  21032. builder.registerTransform( output, attribute );
  21033. return output;
  21034. }
  21035. }
  21036. /**
  21037. * TSL function for creating a storage buffer node.
  21038. *
  21039. * @function
  21040. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21041. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  21042. * @param {Number} [count=0] - The buffer count.
  21043. * @returns {StorageBufferNode}
  21044. */
  21045. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21046. /**
  21047. * @function
  21048. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21049. *
  21050. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21051. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21052. * @param {Number} count - The buffer count.
  21053. * @returns {StorageBufferNode}
  21054. */
  21055. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21056. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21057. return storage( value, type, count ).setPBO( true );
  21058. };
  21059. /** @module Arrays **/
  21060. /**
  21061. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21062. *
  21063. * @function
  21064. * @param {Number} count - The data count.
  21065. * @param {String} [type='float'] - The data type.
  21066. * @returns {StorageBufferNode}
  21067. */
  21068. const attributeArray = ( count, type = 'float' ) => {
  21069. const itemSize = getLengthFromType( type );
  21070. const typedArray = getTypedArrayFromType( type );
  21071. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21072. const node = storage( buffer, type, count );
  21073. return node;
  21074. };
  21075. /**
  21076. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21077. *
  21078. * @function
  21079. * @param {Number} count - The data count.
  21080. * @param {String} [type='float'] - The data type.
  21081. * @returns {StorageBufferNode}
  21082. */
  21083. const instancedArray = ( count, type = 'float' ) => {
  21084. const itemSize = getLengthFromType( type );
  21085. const typedArray = getTypedArrayFromType( type );
  21086. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21087. const node = storage( buffer, type, count );
  21088. return node;
  21089. };
  21090. /** @module VertexColorNode **/
  21091. /**
  21092. * An attribute node for representing vertex colors.
  21093. *
  21094. * @augments module:AttributeNode~AttributeNode
  21095. */
  21096. class VertexColorNode extends AttributeNode {
  21097. static get type() {
  21098. return 'VertexColorNode';
  21099. }
  21100. /**
  21101. * Constructs a new vertex color node.
  21102. *
  21103. * @param {Number} [index=0] - The attribute index.
  21104. */
  21105. constructor( index = 0 ) {
  21106. super( null, 'vec4' );
  21107. /**
  21108. * This flag can be used for type testing.
  21109. *
  21110. * @type {Boolean}
  21111. * @readonly
  21112. * @default true
  21113. */
  21114. this.isVertexColorNode = true;
  21115. /**
  21116. * The attribute index to enable more than one sets of vertex colors.
  21117. *
  21118. * @type {Number}
  21119. * @default 0
  21120. */
  21121. this.index = index;
  21122. }
  21123. /**
  21124. * Overwrites the default implementation by honoring the attribute index.
  21125. *
  21126. * @param {NodeBuilder} builder - The current node builder.
  21127. * @return {String} The attribute name.
  21128. */
  21129. getAttributeName( /*builder*/ ) {
  21130. const index = this.index;
  21131. return 'color' + ( index > 0 ? index : '' );
  21132. }
  21133. generate( builder ) {
  21134. const attributeName = this.getAttributeName( builder );
  21135. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21136. let result;
  21137. if ( geometryAttribute === true ) {
  21138. result = super.generate( builder );
  21139. } else {
  21140. // Vertex color fallback should be white
  21141. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21142. }
  21143. return result;
  21144. }
  21145. serialize( data ) {
  21146. super.serialize( data );
  21147. data.index = this.index;
  21148. }
  21149. deserialize( data ) {
  21150. super.deserialize( data );
  21151. this.index = data.index;
  21152. }
  21153. }
  21154. /**
  21155. * TSL function for creating a reference node.
  21156. *
  21157. * @function
  21158. * @param {Number} index - The attribute index.
  21159. * @returns {VertexColorNode}
  21160. */
  21161. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21162. /** @module PointUVNode **/
  21163. /**
  21164. * A node for representing the uv coordinates of points.
  21165. *
  21166. * Can only be used with a WebGL backend. In WebGPU, point
  21167. * primitives always have the size of one pixel and can thus
  21168. * can't be used as sprite-like objects that display textures.
  21169. *
  21170. * @augments Node
  21171. */
  21172. class PointUVNode extends Node {
  21173. static get type() {
  21174. return 'PointUVNode';
  21175. }
  21176. /**
  21177. * Constructs a new point uv node.
  21178. */
  21179. constructor() {
  21180. super( 'vec2' );
  21181. /**
  21182. * This flag can be used for type testing.
  21183. *
  21184. * @type {Boolean}
  21185. * @readonly
  21186. * @default true
  21187. */
  21188. this.isPointUVNode = true;
  21189. }
  21190. generate( /*builder*/ ) {
  21191. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21192. }
  21193. }
  21194. /**
  21195. * TSL object that represents the uv coordinates of points.
  21196. *
  21197. * @type {PointUVNode}
  21198. */
  21199. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21200. const _e1 = /*@__PURE__*/ new Euler();
  21201. const _m1 = /*@__PURE__*/ new Matrix4();
  21202. /** @module SceneNode **/
  21203. /**
  21204. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21205. * are available for easier use:
  21206. *
  21207. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21208. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21209. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21210. *
  21211. * @augments Node
  21212. */
  21213. class SceneNode extends Node {
  21214. static get type() {
  21215. return 'SceneNode';
  21216. }
  21217. /**
  21218. * Constructs a new scene node.
  21219. *
  21220. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21221. * @param {Scene?} [scene=null] - A reference to the scene.
  21222. */
  21223. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21224. super();
  21225. /**
  21226. * The scope defines the type of scene property that is accessed.
  21227. *
  21228. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21229. */
  21230. this.scope = scope;
  21231. /**
  21232. * A reference to the scene that is going to be accessed.
  21233. *
  21234. * @type {Scene?}
  21235. * @default null
  21236. */
  21237. this.scene = scene;
  21238. }
  21239. /**
  21240. * Depending on the scope, the method returns a different type of node that represents
  21241. * the respective scene property.
  21242. *
  21243. * @param {NodeBuilder} builder - The current node builder.
  21244. * @return {Node} The output node.
  21245. */
  21246. setup( builder ) {
  21247. const scope = this.scope;
  21248. const scene = this.scene !== null ? this.scene : builder.scene;
  21249. let output;
  21250. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21251. output = reference( 'backgroundBlurriness', 'float', scene );
  21252. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21253. output = reference( 'backgroundIntensity', 'float', scene );
  21254. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21255. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21256. const background = scene.background;
  21257. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21258. _e1.copy( scene.backgroundRotation );
  21259. // accommodate left-handed frame
  21260. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21261. _m1.makeRotationFromEuler( _e1 );
  21262. } else {
  21263. _m1.identity();
  21264. }
  21265. return _m1;
  21266. } );
  21267. } else {
  21268. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21269. }
  21270. return output;
  21271. }
  21272. }
  21273. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21274. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21275. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21276. /**
  21277. * TSL object that represents the scene's background blurriness.
  21278. *
  21279. * @type {SceneNode}
  21280. */
  21281. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21282. /**
  21283. * TSL object that represents the scene's background intensity.
  21284. *
  21285. * @type {SceneNode}
  21286. */
  21287. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21288. /**
  21289. * TSL object that represents the scene's background rotation.
  21290. *
  21291. * @type {SceneNode}
  21292. */
  21293. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21294. /** @module StorageTextureNode **/
  21295. /**
  21296. * This special version of a texture node can be used to
  21297. * write data into a storage texture with a compute shader.
  21298. *
  21299. * ```js
  21300. * const storageTexture = new THREE.StorageTexture( width, height );
  21301. *
  21302. * const computeTexture = Fn( ( { storageTexture } ) => {
  21303. *
  21304. * const posX = instanceIndex.modInt( width );
  21305. * const posY = instanceIndex.div( width );
  21306. * const indexUV = uvec2( posX, posY );
  21307. *
  21308. * // generate RGB values
  21309. *
  21310. * const r = 1;
  21311. * const g = 1;
  21312. * const b = 1;
  21313. *
  21314. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21315. *
  21316. * } );
  21317. *
  21318. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21319. * renderer.computeAsync( computeNode );
  21320. * ```
  21321. *
  21322. * This node can only be used with a WebGPU backend.
  21323. *
  21324. * @augments module:TextureNode~TextureNode
  21325. */
  21326. class StorageTextureNode extends TextureNode {
  21327. static get type() {
  21328. return 'StorageTextureNode';
  21329. }
  21330. /**
  21331. * Constructs a new storage texture node.
  21332. *
  21333. * @param {StorageTexture} value - The storage texture.
  21334. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21335. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21336. */
  21337. constructor( value, uvNode, storeNode = null ) {
  21338. super( value, uvNode );
  21339. /**
  21340. * The value node that should be stored in the texture.
  21341. *
  21342. * @type {Node?}
  21343. * @default null
  21344. */
  21345. this.storeNode = storeNode;
  21346. /**
  21347. * This flag can be used for type testing.
  21348. *
  21349. * @type {Boolean}
  21350. * @readonly
  21351. * @default true
  21352. */
  21353. this.isStorageTextureNode = true;
  21354. /**
  21355. * The access type of the texture node.
  21356. *
  21357. * @type {String}
  21358. * @default 'writeOnly'
  21359. */
  21360. this.access = NodeAccess.WRITE_ONLY;
  21361. }
  21362. /**
  21363. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21364. *
  21365. * @param {NodeBuilder} builder - The current node builder.
  21366. * @return {String} The input type.
  21367. */
  21368. getInputType( /*builder*/ ) {
  21369. return 'storageTexture';
  21370. }
  21371. setup( builder ) {
  21372. super.setup( builder );
  21373. const properties = builder.getNodeProperties( this );
  21374. properties.storeNode = this.storeNode;
  21375. }
  21376. /**
  21377. * Defines the node access.
  21378. *
  21379. * @param {String} value - The node access.
  21380. * @return {StorageTextureNode} A reference to this node.
  21381. */
  21382. setAccess( value ) {
  21383. this.access = value;
  21384. return this;
  21385. }
  21386. /**
  21387. * Generates the code snippet of the stroge node. If no `storeNode`
  21388. * is defined, the texture node is generated as normal texture.
  21389. *
  21390. * @param {NodeBuilder} builder - The current node builder.
  21391. * @param {String} output - The current output.
  21392. * @return {String} The generated code snippet.
  21393. */
  21394. generate( builder, output ) {
  21395. let snippet;
  21396. if ( this.storeNode !== null ) {
  21397. snippet = this.generateStore( builder );
  21398. } else {
  21399. snippet = super.generate( builder, output );
  21400. }
  21401. return snippet;
  21402. }
  21403. /**
  21404. * Convenience method for configuring a read/write node access.
  21405. *
  21406. * @return {StorageTextureNode} A reference to this node.
  21407. */
  21408. toReadWrite() {
  21409. return this.setAccess( NodeAccess.READ_WRITE );
  21410. }
  21411. /**
  21412. * Convenience method for configuring a read-only node access.
  21413. *
  21414. * @return {StorageTextureNode} A reference to this node.
  21415. */
  21416. toReadOnly() {
  21417. return this.setAccess( NodeAccess.READ_ONLY );
  21418. }
  21419. /**
  21420. * Convenience method for configuring a write-only node access.
  21421. *
  21422. * @return {StorageTextureNode} A reference to this node.
  21423. */
  21424. toWriteOnly() {
  21425. return this.setAccess( NodeAccess.WRITE_ONLY );
  21426. }
  21427. /**
  21428. * Generates the code snippet of the storage texture node.
  21429. *
  21430. * @param {NodeBuilder} builder - The current node builder.
  21431. */
  21432. generateStore( builder ) {
  21433. const properties = builder.getNodeProperties( this );
  21434. const { uvNode, storeNode } = properties;
  21435. const textureProperty = super.generate( builder, 'property' );
  21436. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21437. const storeSnippet = storeNode.build( builder, 'vec4' );
  21438. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21439. builder.addLineFlowCode( snippet, this );
  21440. }
  21441. }
  21442. /**
  21443. * TSL function for creating a storage texture node.
  21444. *
  21445. * @function
  21446. * @param {StorageTexture} value - The storage texture.
  21447. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21448. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21449. * @returns {StorageTextureNode}
  21450. */
  21451. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21452. /**
  21453. * TODO: Explain difference to `storageTexture()`.
  21454. *
  21455. * @function
  21456. * @param {StorageTexture} value - The storage texture.
  21457. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21458. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21459. * @returns {StorageTextureNode}
  21460. */
  21461. const textureStore = ( value, uvNode, storeNode ) => {
  21462. const node = storageTexture( value, uvNode, storeNode );
  21463. if ( storeNode !== null ) node.append();
  21464. return node;
  21465. };
  21466. /** @module UserDataNode **/
  21467. /**
  21468. * A special type of reference node that allows to link values in
  21469. * `userData` fields to node objects.
  21470. * ```js
  21471. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21472. *
  21473. * const material = new THREE.SpriteNodeMaterial();
  21474. * material.rotationNode = userData( 'rotation', 'float' );
  21475. * ```
  21476. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21477. * will automatically be updated when the `rotation` user data field changes.
  21478. *
  21479. * @augments module:ReferenceNode~ReferenceNode
  21480. */
  21481. class UserDataNode extends ReferenceNode {
  21482. static get type() {
  21483. return 'UserDataNode';
  21484. }
  21485. /**
  21486. * Constructs a new user data node.
  21487. *
  21488. * @param {String} property - The property name that should be referenced by the node.
  21489. * @param {String} inputType - The node data type of the reference.
  21490. * @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.
  21491. */
  21492. constructor( property, inputType, userData = null ) {
  21493. super( property, inputType, userData );
  21494. /**
  21495. * A reference to the `userData` object. If not provided, the `userData`
  21496. * property of the 3D object that uses the node material is evaluated.
  21497. *
  21498. * @type {Object?}
  21499. * @default null
  21500. */
  21501. this.userData = userData;
  21502. }
  21503. /**
  21504. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21505. * `userData` field.
  21506. *
  21507. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21508. * @return {Object} A reference to the `userData` field.
  21509. */
  21510. updateReference( state ) {
  21511. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21512. return this.reference;
  21513. }
  21514. }
  21515. /**
  21516. * TSL function for creating a user data node.
  21517. *
  21518. * @function
  21519. * @param {String} name - The property name that should be referenced by the node.
  21520. * @param {String} inputType - The node data type of the reference.
  21521. * @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.
  21522. * @returns {UserDataNode}
  21523. */
  21524. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21525. const _objectData = new WeakMap();
  21526. /** @module VelocityNode **/
  21527. /**
  21528. * A node for representing motion or velocity vectors. Foundation
  21529. * for advanced post processing effects like motion blur or TRAA.
  21530. *
  21531. * The node keeps track of the model, view and projection matrices
  21532. * of the previous frame and uses them to compute offsets in NDC space.
  21533. * These offsets represent the final velocity.
  21534. *
  21535. * @augments TempNode
  21536. */
  21537. class VelocityNode extends TempNode {
  21538. static get type() {
  21539. return 'VelocityNode';
  21540. }
  21541. /**
  21542. * Constructs a new vertex color node.
  21543. */
  21544. constructor() {
  21545. super( 'vec2' );
  21546. /**
  21547. * The current projection matrix.
  21548. *
  21549. * @type {Matrix4?}
  21550. * @default null
  21551. */
  21552. this.projectionMatrix = null;
  21553. /**
  21554. * Overwritten since velocity nodes are updated per object.
  21555. *
  21556. * @type {String}
  21557. * @default 'object'
  21558. */
  21559. this.updateType = NodeUpdateType.OBJECT;
  21560. /**
  21561. * Overwritten since velocity nodes save data after the update.
  21562. *
  21563. * @type {String}
  21564. * @default 'object'
  21565. */
  21566. this.updateAfterType = NodeUpdateType.OBJECT;
  21567. /**
  21568. * Uniform node representing the previous model matrix in world space.
  21569. *
  21570. * @type {UniformNode<mat4>}
  21571. * @default null
  21572. */
  21573. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21574. /**
  21575. * Uniform node representing the previous projection matrix.
  21576. *
  21577. * @type {UniformNode<mat4>}
  21578. * @default null
  21579. */
  21580. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21581. /**
  21582. * Uniform node representing the previous view matrix.
  21583. *
  21584. * @type {UniformNode<mat4>}
  21585. * @default null
  21586. */
  21587. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21588. }
  21589. /**
  21590. * Sets the given projection matrix.
  21591. *
  21592. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21593. */
  21594. setProjectionMatrix( projectionMatrix ) {
  21595. this.projectionMatrix = projectionMatrix;
  21596. }
  21597. /**
  21598. * Updates velocity specific uniforms.
  21599. *
  21600. * @param {NodeFrame} frame - A reference to the current node frame.
  21601. */
  21602. update( { frameId, camera, object } ) {
  21603. const previousModelMatrix = getPreviousMatrix( object );
  21604. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21605. //
  21606. const cameraData = getData( camera );
  21607. if ( cameraData.frameId !== frameId ) {
  21608. cameraData.frameId = frameId;
  21609. if ( cameraData.previousProjectionMatrix === undefined ) {
  21610. cameraData.previousProjectionMatrix = new Matrix4();
  21611. cameraData.previousCameraViewMatrix = new Matrix4();
  21612. cameraData.currentProjectionMatrix = new Matrix4();
  21613. cameraData.currentCameraViewMatrix = new Matrix4();
  21614. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21615. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21616. } else {
  21617. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21618. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21619. }
  21620. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21621. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21622. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21623. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21624. }
  21625. }
  21626. /**
  21627. * Overwritten to updated velocity specific uniforms.
  21628. *
  21629. * @param {NodeFrame} frame - A reference to the current node frame.
  21630. */
  21631. updateAfter( { object } ) {
  21632. getPreviousMatrix( object ).copy( object.matrixWorld );
  21633. }
  21634. /**
  21635. * Implements the velocity computation based on the previous and current vertex data.
  21636. *
  21637. * @param {NodeBuilder} builder - A reference to the current node builder.
  21638. * @return {Node<vec2>} The motion vector.
  21639. */
  21640. setup( /*builder*/ ) {
  21641. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21642. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21643. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21644. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21645. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21646. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21647. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21648. return velocity;
  21649. }
  21650. }
  21651. function getData( object ) {
  21652. let objectData = _objectData.get( object );
  21653. if ( objectData === undefined ) {
  21654. objectData = {};
  21655. _objectData.set( object, objectData );
  21656. }
  21657. return objectData;
  21658. }
  21659. function getPreviousMatrix( object, index = 0 ) {
  21660. const objectData = getData( object );
  21661. let matrix = objectData[ index ];
  21662. if ( matrix === undefined ) {
  21663. objectData[ index ] = matrix = new Matrix4();
  21664. }
  21665. return matrix;
  21666. }
  21667. /**
  21668. * TSL object that represents the velocity of a render pass.
  21669. *
  21670. * @type {VelocityNode}
  21671. */
  21672. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21673. /** @module BlendModes **/
  21674. /**
  21675. * Represents a "Color Burn" blend mode.
  21676. *
  21677. * It's designed to darken the base layer's colors based on the color of the blend layer.
  21678. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  21679. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  21680. *
  21681. * @method
  21682. * @param {Node<vec3>} base - The base color.
  21683. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  21684. * @return {Node<vec3>} The result.
  21685. */
  21686. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21687. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21688. } ).setLayout( {
  21689. name: 'blendBurn',
  21690. type: 'vec3',
  21691. inputs: [
  21692. { name: 'base', type: 'vec3' },
  21693. { name: 'blend', type: 'vec3' }
  21694. ]
  21695. } );
  21696. /**
  21697. * Represents a "Color Dodge" blend mode.
  21698. *
  21699. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  21700. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  21701. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  21702. *
  21703. * @method
  21704. * @param {Node<vec3>} base - The base color.
  21705. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21706. * @return {Node<vec3>} The result.
  21707. */
  21708. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21709. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21710. } ).setLayout( {
  21711. name: 'blendDodge',
  21712. type: 'vec3',
  21713. inputs: [
  21714. { name: 'base', type: 'vec3' },
  21715. { name: 'blend', type: 'vec3' }
  21716. ]
  21717. } );
  21718. /**
  21719. * Represents a "Screen" blend mode.
  21720. *
  21721. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  21722. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  21723. * effects.
  21724. *
  21725. * @method
  21726. * @param {Node<vec3>} base - The base color.
  21727. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21728. * @return {Node<vec3>} The result.
  21729. */
  21730. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21731. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21732. } ).setLayout( {
  21733. name: 'blendScreen',
  21734. type: 'vec3',
  21735. inputs: [
  21736. { name: 'base', type: 'vec3' },
  21737. { name: 'blend', type: 'vec3' }
  21738. ]
  21739. } );
  21740. /**
  21741. * Represents a "Overlay" blend mode.
  21742. *
  21743. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  21744. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  21745. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  21746. *
  21747. * @method
  21748. * @param {Node<vec3>} base - The base color.
  21749. * @param {Node<vec3>} blend - The blend color
  21750. * @return {Node<vec3>} The result.
  21751. */
  21752. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21753. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21754. } ).setLayout( {
  21755. name: 'blendOverlay',
  21756. type: 'vec3',
  21757. inputs: [
  21758. { name: 'base', type: 'vec3' },
  21759. { name: 'blend', type: 'vec3' }
  21760. ]
  21761. } );
  21762. /**
  21763. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  21764. * It assumes both input colors have non-preumiltiplied alpha.
  21765. *
  21766. * @method
  21767. * @param {Node<vec4>} base - The base color.
  21768. * @param {Node<vec4>} blend - The blend color
  21769. * @return {Node<vec4>} The result.
  21770. */
  21771. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21772. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21773. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21774. } ).setLayout( {
  21775. name: 'blendColor',
  21776. type: 'vec4',
  21777. inputs: [
  21778. { name: 'base', type: 'vec4' },
  21779. { name: 'blend', type: 'vec4' }
  21780. ]
  21781. } );
  21782. // deprecated
  21783. /**
  21784. * @function
  21785. * @deprecated since r171. Use {@link blendBurn} instead.
  21786. *
  21787. * @param {...any} params
  21788. * @returns {Function}
  21789. */
  21790. const burn = ( ...params ) => { // @deprecated, r171
  21791. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21792. return blendBurn( params );
  21793. };
  21794. /**
  21795. * @function
  21796. * @deprecated since r171. Use {@link blendDodge} instead.
  21797. *
  21798. * @param {...any} params
  21799. * @returns {Function}
  21800. */
  21801. const dodge = ( ...params ) => { // @deprecated, r171
  21802. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21803. return blendDodge( params );
  21804. };
  21805. /**
  21806. * @method
  21807. * @deprecated since r171. Use {@link blendScreen} instead.
  21808. *
  21809. * @param {...any} params
  21810. * @returns {Function}
  21811. */
  21812. const screen = ( ...params ) => { // @deprecated, r171
  21813. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21814. return blendScreen( params );
  21815. };
  21816. /**
  21817. * @method
  21818. * @deprecated since r171. Use {@link blendOverlay} instead.
  21819. *
  21820. * @param {...any} params
  21821. * @returns {Function}
  21822. */
  21823. const overlay = ( ...params ) => { // @deprecated, r171
  21824. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21825. return blendOverlay( params );
  21826. };
  21827. /** @module ColorAdjustment **/
  21828. /**
  21829. * Computes a grayscale value for the given RGB color value.
  21830. *
  21831. * @method
  21832. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21833. * @return {Node<vec3>} The grayscale color.
  21834. */
  21835. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21836. return luminance( color.rgb );
  21837. } );
  21838. /**
  21839. * Super-saturates or desaturates the given RGB color.
  21840. *
  21841. * @method
  21842. * @param {Node<vec3>} color - The input color.
  21843. * @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.
  21844. * @return {Node<vec3>} The saturated color.
  21845. */
  21846. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21847. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21848. } );
  21849. /**
  21850. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21851. * in a more natural and visually appealing image with enhanced color depth
  21852. * compared to {@link ColorAdjustment#saturation}.
  21853. *
  21854. * @method
  21855. * @param {Node<vec3>} color - The input color.
  21856. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21857. * @return {Node<vec3>} The updated color.
  21858. */
  21859. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21860. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21861. const mx = color.r.max( color.g.max( color.b ) );
  21862. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21863. return mix( color.rgb, mx, amt );
  21864. } );
  21865. /**
  21866. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21867. *
  21868. * @method
  21869. * @param {Node<vec3>} color - The input color.
  21870. * @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.
  21871. * @return {Node<vec3>} The updated color.
  21872. */
  21873. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21874. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21875. const cosAngle = adjustment.cos();
  21876. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21877. } );
  21878. /**
  21879. * Computes the luminance for the given RGB color value.
  21880. *
  21881. * @method
  21882. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21883. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21884. * @return {Node<vec3>} The luminance.
  21885. */
  21886. const luminance = (
  21887. color,
  21888. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21889. ) => dot( color, luminanceCoefficients );
  21890. /**
  21891. * Color Decision List (CDL) v1.2
  21892. *
  21893. * Compact representation of color grading information, defined by slope, offset, power, and
  21894. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21895. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21896. *
  21897. * @method
  21898. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21899. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21900. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21901. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21902. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21903. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21904. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21905. *
  21906. * References:
  21907. * - ASC CDL v1.2
  21908. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21909. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21910. */
  21911. const cdl = /*@__PURE__*/ Fn( ( [
  21912. color,
  21913. slope = vec3( 1 ),
  21914. offset = vec3( 0 ),
  21915. power = vec3( 1 ),
  21916. saturation = float( 1 ),
  21917. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21918. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21919. ] ) => {
  21920. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21921. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21922. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21923. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21924. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21925. const pv = v.pow( power ).toVar();
  21926. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21927. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21928. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21929. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21930. return vec4( v.rgb, color.a );
  21931. } );
  21932. /** @module PosterizeNode **/
  21933. /**
  21934. * Represents a posterize effect which reduces the number of colors
  21935. * in an image, resulting in a more blocky and stylized appearance.
  21936. *
  21937. * @augments TempNode
  21938. */
  21939. class PosterizeNode extends TempNode {
  21940. static get type() {
  21941. return 'PosterizeNode';
  21942. }
  21943. /**
  21944. * Constructs a new posterize node.
  21945. *
  21946. * @param {Node} sourceNode - The input color.
  21947. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21948. */
  21949. constructor( sourceNode, stepsNode ) {
  21950. super();
  21951. /**
  21952. * The input color.
  21953. *
  21954. * @type {Node}
  21955. */
  21956. this.sourceNode = sourceNode;
  21957. /**
  21958. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21959. *
  21960. * @type {Node}
  21961. */
  21962. this.stepsNode = stepsNode;
  21963. }
  21964. setup() {
  21965. const { sourceNode, stepsNode } = this;
  21966. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21967. }
  21968. }
  21969. /**
  21970. * TSL function for creating a posterize node.
  21971. *
  21972. * @function
  21973. * @param {Node} sourceNode - The input color.
  21974. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21975. * @returns {PosterizeNode}
  21976. */
  21977. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21978. /** @module PassNode **/
  21979. const _size = /*@__PURE__*/ new Vector2();
  21980. /**
  21981. * Represents the texture of a pass node.
  21982. *
  21983. * @augments module:TextureNode~TextureNode
  21984. */
  21985. class PassTextureNode extends TextureNode {
  21986. static get type() {
  21987. return 'PassTextureNode';
  21988. }
  21989. /**
  21990. * Constructs a new pass texture node.
  21991. *
  21992. * @param {PassNode} passNode - The pass node.
  21993. * @param {Texture} texture - The output texture.
  21994. */
  21995. constructor( passNode, texture ) {
  21996. super( texture );
  21997. /**
  21998. * A reference to the pass node.
  21999. *
  22000. * @type {PassNode}
  22001. */
  22002. this.passNode = passNode;
  22003. this.setUpdateMatrix( false );
  22004. }
  22005. setup( builder ) {
  22006. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22007. return super.setup( builder );
  22008. }
  22009. clone() {
  22010. return new this.constructor( this.passNode, this.value );
  22011. }
  22012. }
  22013. /**
  22014. * An extension of `PassTextureNode` which allows to manage more than one
  22015. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22016. *
  22017. * @augments module:PassTextureNode~PassTextureNode
  22018. */
  22019. class PassMultipleTextureNode extends PassTextureNode {
  22020. static get type() {
  22021. return 'PassMultipleTextureNode';
  22022. }
  22023. /**
  22024. * Constructs a new pass texture node.
  22025. *
  22026. * @param {PassNode} passNode - The pass node.
  22027. * @param {String} textureName - The output texture name.
  22028. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22029. */
  22030. constructor( passNode, textureName, previousTexture = false ) {
  22031. // null is passed to the super call since this class does not
  22032. // use an external texture for rendering pass data into. Instead
  22033. // the texture is managed by the pass node itself
  22034. super( passNode, null );
  22035. /**
  22036. * The output texture name.
  22037. *
  22038. * @type {String}
  22039. */
  22040. this.textureName = textureName;
  22041. /**
  22042. * Whether previous frame data should be used or not.
  22043. *
  22044. * @type {Boolean}
  22045. */
  22046. this.previousTexture = previousTexture;
  22047. }
  22048. /**
  22049. * Updates the texture reference of this node.
  22050. */
  22051. updateTexture() {
  22052. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22053. }
  22054. setup( builder ) {
  22055. this.updateTexture();
  22056. return super.setup( builder );
  22057. }
  22058. clone() {
  22059. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22060. }
  22061. }
  22062. /**
  22063. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22064. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22065. * via MRT for further processing.
  22066. *
  22067. * ```js
  22068. * const postProcessing = new PostProcessing( renderer );
  22069. *
  22070. * const scenePass = pass( scene, camera );
  22071. *
  22072. * postProcessing.outputNode = scenePass;
  22073. * ```
  22074. *
  22075. * @augments TempNode
  22076. */
  22077. class PassNode extends TempNode {
  22078. static get type() {
  22079. return 'PassNode';
  22080. }
  22081. /**
  22082. * Constructs a new pass node.
  22083. *
  22084. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22085. * @param {Scene} scene - A reference to the scene.
  22086. * @param {Camera} camera - A reference to the camera.
  22087. * @param {Object} options - Options for the internal render target.
  22088. */
  22089. constructor( scope, scene, camera, options = {} ) {
  22090. super( 'vec4' );
  22091. /**
  22092. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22093. *
  22094. * @type {('color'|'depth')}
  22095. */
  22096. this.scope = scope;
  22097. /**
  22098. * A reference to the scene.
  22099. *
  22100. * @type {Scene}
  22101. */
  22102. this.scene = scene;
  22103. /**
  22104. * A reference to the camera.
  22105. *
  22106. * @type {Camera}
  22107. */
  22108. this.camera = camera;
  22109. /**
  22110. * Options for the internal render target.
  22111. *
  22112. * @type {Object}
  22113. */
  22114. this.options = options;
  22115. /**
  22116. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22117. *
  22118. * @private
  22119. * @type {Number}
  22120. * @default 1
  22121. */
  22122. this._pixelRatio = 1;
  22123. /**
  22124. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22125. * @private
  22126. * @type {Number}
  22127. * @default 1
  22128. */
  22129. this._width = 1;
  22130. /**
  22131. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22132. * @private
  22133. * @type {Number}
  22134. * @default 1
  22135. */
  22136. this._height = 1;
  22137. const depthTexture = new DepthTexture();
  22138. depthTexture.isRenderTargetTexture = true;
  22139. //depthTexture.type = FloatType;
  22140. depthTexture.name = 'depth';
  22141. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22142. renderTarget.texture.name = 'output';
  22143. renderTarget.depthTexture = depthTexture;
  22144. /**
  22145. * The pass's render target.
  22146. *
  22147. * @type {RenderTarget}
  22148. */
  22149. this.renderTarget = renderTarget;
  22150. /**
  22151. * A dictionary holding the internal result textures.
  22152. *
  22153. * @private
  22154. * @type {Object<String, Texture>}
  22155. */
  22156. this._textures = {
  22157. output: renderTarget.texture,
  22158. depth: depthTexture
  22159. };
  22160. /**
  22161. * A dictionary holding the internal texture nodes.
  22162. *
  22163. * @private
  22164. * @type {Object<String, TextureNode>}
  22165. */
  22166. this._textureNodes = {};
  22167. /**
  22168. * A dictionary holding the internal depth nodes.
  22169. *
  22170. * @private
  22171. * @type {Object}
  22172. */
  22173. this._linearDepthNodes = {};
  22174. /**
  22175. * A dictionary holding the internal viewZ nodes.
  22176. *
  22177. * @private
  22178. * @type {Object}
  22179. */
  22180. this._viewZNodes = {};
  22181. /**
  22182. * A dictionary holding the texture data of the previous frame.
  22183. * Used for computing velocity/motion vectors.
  22184. *
  22185. * @private
  22186. * @type {Object<String, Texture>}
  22187. */
  22188. this._previousTextures = {};
  22189. /**
  22190. * A dictionary holding the texture nodes of the previous frame.
  22191. * Used for computing velocity/motion vectors.
  22192. *
  22193. * @private
  22194. * @type {Object<String, TextureNode>}
  22195. */
  22196. this._previousTextureNodes = {};
  22197. /**
  22198. * The `near` property of the camera as a uniform.
  22199. *
  22200. * @private
  22201. * @type {UniformNode}
  22202. */
  22203. this._cameraNear = uniform( 0 );
  22204. /**
  22205. * The `far` property of the camera as a uniform.
  22206. *
  22207. * @private
  22208. * @type {UniformNode}
  22209. */
  22210. this._cameraFar = uniform( 0 );
  22211. /**
  22212. * A MRT node configuring the MRT settings.
  22213. *
  22214. * @private
  22215. * @type {MRTNode?}
  22216. * @default null
  22217. */
  22218. this._mrt = null;
  22219. /**
  22220. * This flag can be used for type testing.
  22221. *
  22222. * @type {Boolean}
  22223. * @readonly
  22224. * @default true
  22225. */
  22226. this.isPassNode = true;
  22227. /**
  22228. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22229. * scene once per frame in its {@link PassNode#updateBefore} method.
  22230. *
  22231. * @type {String}
  22232. * @default 'frame'
  22233. */
  22234. this.updateBeforeType = NodeUpdateType.FRAME;
  22235. }
  22236. /**
  22237. * Sets the given MRT node to setup MRT for this pass.
  22238. *
  22239. * @param {MRTNode} mrt - The MRT object.
  22240. * @return {PassNode} A reference to this pass.
  22241. */
  22242. setMRT( mrt ) {
  22243. this._mrt = mrt;
  22244. return this;
  22245. }
  22246. /**
  22247. * Returns the current MRT node.
  22248. *
  22249. * @return {MRTNode} The current MRT node.
  22250. */
  22251. getMRT() {
  22252. return this._mrt;
  22253. }
  22254. /**
  22255. * The method is overwritten so it always returns `true`.
  22256. *
  22257. * @return {Boolean} Whether this node is global or not.
  22258. */
  22259. isGlobal() {
  22260. return true;
  22261. }
  22262. /**
  22263. * Returns the texture for the given output name.
  22264. *
  22265. * @param {String} name - The output name to get the texture for.
  22266. * @return {Texture} The texture.
  22267. */
  22268. getTexture( name ) {
  22269. let texture = this._textures[ name ];
  22270. if ( texture === undefined ) {
  22271. const refTexture = this.renderTarget.texture;
  22272. texture = refTexture.clone();
  22273. texture.name = name;
  22274. this._textures[ name ] = texture;
  22275. this.renderTarget.textures.push( texture );
  22276. }
  22277. return texture;
  22278. }
  22279. /**
  22280. * Returns the texture holding the data of the previous frame for the given output name.
  22281. *
  22282. * @param {String} name - The output name to get the texture for.
  22283. * @return {Texture} The texture holding the data of the previous frame.
  22284. */
  22285. getPreviousTexture( name ) {
  22286. let texture = this._previousTextures[ name ];
  22287. if ( texture === undefined ) {
  22288. texture = this.getTexture( name ).clone();
  22289. this._previousTextures[ name ] = texture;
  22290. }
  22291. return texture;
  22292. }
  22293. /**
  22294. * Switches current and previous textures for the given output name.
  22295. *
  22296. * @param {String} name - The output name.
  22297. */
  22298. toggleTexture( name ) {
  22299. const prevTexture = this._previousTextures[ name ];
  22300. if ( prevTexture !== undefined ) {
  22301. const texture = this._textures[ name ];
  22302. const index = this.renderTarget.textures.indexOf( texture );
  22303. this.renderTarget.textures[ index ] = prevTexture;
  22304. this._textures[ name ] = prevTexture;
  22305. this._previousTextures[ name ] = texture;
  22306. this._textureNodes[ name ].updateTexture();
  22307. this._previousTextureNodes[ name ].updateTexture();
  22308. }
  22309. }
  22310. /**
  22311. * Returns the texture node for the given output name.
  22312. *
  22313. * @param {String} [name='output'] - The output name to get the texture node for.
  22314. * @return {TextureNode} The texture node.
  22315. */
  22316. getTextureNode( name = 'output' ) {
  22317. let textureNode = this._textureNodes[ name ];
  22318. if ( textureNode === undefined ) {
  22319. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22320. textureNode.updateTexture();
  22321. this._textureNodes[ name ] = textureNode;
  22322. }
  22323. return textureNode;
  22324. }
  22325. /**
  22326. * Returns the previous texture node for the given output name.
  22327. *
  22328. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22329. * @return {TextureNode} The previous texture node.
  22330. */
  22331. getPreviousTextureNode( name = 'output' ) {
  22332. let textureNode = this._previousTextureNodes[ name ];
  22333. if ( textureNode === undefined ) {
  22334. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22335. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22336. textureNode.updateTexture();
  22337. this._previousTextureNodes[ name ] = textureNode;
  22338. }
  22339. return textureNode;
  22340. }
  22341. /**
  22342. * Returns a viewZ node of this pass.
  22343. *
  22344. * @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.
  22345. * @return {Node} The viewZ node.
  22346. */
  22347. getViewZNode( name = 'depth' ) {
  22348. let viewZNode = this._viewZNodes[ name ];
  22349. if ( viewZNode === undefined ) {
  22350. const cameraNear = this._cameraNear;
  22351. const cameraFar = this._cameraFar;
  22352. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22353. }
  22354. return viewZNode;
  22355. }
  22356. /**
  22357. * Returns a linear depth node of this pass.
  22358. *
  22359. * @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.
  22360. * @return {Node} The linear depth node.
  22361. */
  22362. getLinearDepthNode( name = 'depth' ) {
  22363. let linearDepthNode = this._linearDepthNodes[ name ];
  22364. if ( linearDepthNode === undefined ) {
  22365. const cameraNear = this._cameraNear;
  22366. const cameraFar = this._cameraFar;
  22367. const viewZNode = this.getViewZNode( name );
  22368. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22369. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22370. }
  22371. return linearDepthNode;
  22372. }
  22373. setup( { renderer } ) {
  22374. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22375. // Disable MSAA for WebGL backend for now
  22376. if ( renderer.backend.isWebGLBackend === true ) {
  22377. this.renderTarget.samples = 0;
  22378. }
  22379. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22380. }
  22381. updateBefore( frame ) {
  22382. const { renderer } = frame;
  22383. const { scene, camera } = this;
  22384. this._pixelRatio = renderer.getPixelRatio();
  22385. const size = renderer.getSize( _size );
  22386. this.setSize( size.width, size.height );
  22387. const currentRenderTarget = renderer.getRenderTarget();
  22388. const currentMRT = renderer.getMRT();
  22389. this._cameraNear.value = camera.near;
  22390. this._cameraFar.value = camera.far;
  22391. for ( const name in this._previousTextures ) {
  22392. this.toggleTexture( name );
  22393. }
  22394. renderer.setRenderTarget( this.renderTarget );
  22395. renderer.setMRT( this._mrt );
  22396. renderer.render( scene, camera );
  22397. renderer.setRenderTarget( currentRenderTarget );
  22398. renderer.setMRT( currentMRT );
  22399. }
  22400. /**
  22401. * Sets the size of the pass's render target. Honors the pixel ratio.
  22402. *
  22403. * @param {Number} width - The width to set.
  22404. * @param {Number} height - The height to set.
  22405. */
  22406. setSize( width, height ) {
  22407. this._width = width;
  22408. this._height = height;
  22409. const effectiveWidth = this._width * this._pixelRatio;
  22410. const effectiveHeight = this._height * this._pixelRatio;
  22411. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22412. }
  22413. /**
  22414. * Sets the pixel ratio the pass's render target and updates the size.
  22415. *
  22416. * @param {Number} pixelRatio - The pixel ratio to set.
  22417. */
  22418. setPixelRatio( pixelRatio ) {
  22419. this._pixelRatio = pixelRatio;
  22420. this.setSize( this._width, this._height );
  22421. }
  22422. /**
  22423. * Frees internal resources. Should be called when the node is no longer in use.
  22424. */
  22425. dispose() {
  22426. this.renderTarget.dispose();
  22427. }
  22428. }
  22429. PassNode.COLOR = 'color';
  22430. PassNode.DEPTH = 'depth';
  22431. /**
  22432. * TSL function for creating a pass node.
  22433. *
  22434. * @function
  22435. * @param {Scene} scene - A reference to the scene.
  22436. * @param {Camera} camera - A reference to the camera.
  22437. * @param {Object} options - Options for the internal render target.
  22438. * @returns {PassNode}
  22439. */
  22440. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22441. /**
  22442. * TSL function for creating a pass texture node.
  22443. *
  22444. * @function
  22445. * @param {PassNode} pass - The pass node.
  22446. * @param {Texture} texture - The output texture.
  22447. * @returns {PassTextureNode}
  22448. */
  22449. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22450. /**
  22451. * TSL function for creating a depth pass node.
  22452. *
  22453. * @function
  22454. * @param {Scene} scene - A reference to the scene.
  22455. * @param {Camera} camera - A reference to the camera.
  22456. * @param {Object} options - Options for the internal render target.
  22457. * @returns {PassNode}
  22458. */
  22459. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22460. /** @module ToonOutlinePassNode **/
  22461. /**
  22462. * Represents a render pass for producing a toon outline effect on compatible objects.
  22463. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22464. * will receive the outline.
  22465. *
  22466. * ```js
  22467. * const postProcessing = new PostProcessing( renderer );
  22468. *
  22469. * const scenePass = toonOutlinePass( scene, camera );
  22470. *
  22471. * postProcessing.outputNode = scenePass;
  22472. * ```
  22473. * @augments PassNode
  22474. */
  22475. class ToonOutlinePassNode extends PassNode {
  22476. static get type() {
  22477. return 'ToonOutlinePassNode';
  22478. }
  22479. /**
  22480. * Constructs a new outline pass node.
  22481. *
  22482. * @param {Scene} scene - A reference to the scene.
  22483. * @param {Camera} camera - A reference to the camera.
  22484. * @param {Node} colorNode - Defines the outline's color.
  22485. * @param {Node} thicknessNode - Defines the outline's thickness.
  22486. * @param {Node} alphaNode - Defines the outline's alpha.
  22487. */
  22488. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22489. super( PassNode.COLOR, scene, camera );
  22490. /**
  22491. * Defines the outline's color.
  22492. *
  22493. * @type {Node}
  22494. */
  22495. this.colorNode = colorNode;
  22496. /**
  22497. * Defines the outline's thickness.
  22498. *
  22499. * @type {Node}
  22500. */
  22501. this.thicknessNode = thicknessNode;
  22502. /**
  22503. * Defines the outline's alpha.
  22504. *
  22505. * @type {Node}
  22506. */
  22507. this.alphaNode = alphaNode;
  22508. /**
  22509. * An internal material cache.
  22510. *
  22511. * @private
  22512. * @type {WeakMap<Material, NodeMaterial>}
  22513. */
  22514. this._materialCache = new WeakMap();
  22515. }
  22516. updateBefore( frame ) {
  22517. const { renderer } = frame;
  22518. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22519. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22520. // only render outline for supported materials
  22521. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22522. if ( material.wireframe === false ) {
  22523. const outlineMaterial = this._getOutlineMaterial( material );
  22524. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22525. }
  22526. }
  22527. // default
  22528. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22529. } );
  22530. super.updateBefore( frame );
  22531. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22532. }
  22533. /**
  22534. * Creates the material used for outline rendering.
  22535. *
  22536. * @private
  22537. * @return {NodeMaterial} The outline material.
  22538. */
  22539. _createMaterial() {
  22540. const material = new NodeMaterial();
  22541. material.isMeshToonOutlineMaterial = true;
  22542. material.name = 'Toon_Outline';
  22543. material.side = BackSide;
  22544. // vertex node
  22545. const outlineNormal = normalLocal.negate();
  22546. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22547. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22548. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22549. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22550. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22551. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22552. // color node
  22553. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22554. return material;
  22555. }
  22556. /**
  22557. * For the given toon material, this method returns a corresponding
  22558. * outline material.
  22559. *
  22560. * @private
  22561. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22562. * @return {NodeMaterial} The outline material.
  22563. */
  22564. _getOutlineMaterial( originalMaterial ) {
  22565. let outlineMaterial = this._materialCache.get( originalMaterial );
  22566. if ( outlineMaterial === undefined ) {
  22567. outlineMaterial = this._createMaterial();
  22568. this._materialCache.set( originalMaterial, outlineMaterial );
  22569. }
  22570. return outlineMaterial;
  22571. }
  22572. }
  22573. /**
  22574. * TSL function for creating a toon outline pass node.
  22575. *
  22576. * @function
  22577. * @param {Scene} scene - A reference to the scene.
  22578. * @param {Camera} camera - A reference to the camera.
  22579. * @param {Color} color - Defines the outline's color.
  22580. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22581. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22582. * @returns {ToonOutlinePassNode}
  22583. */
  22584. 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 ) ) );
  22585. /** @module ToneMappingFunctions **/
  22586. /**
  22587. * Linear tone mapping, exposure only.
  22588. *
  22589. * @method
  22590. * @param {Node<vec3>} color - The color that should be tone mapped.
  22591. * @param {Node<float>} exposure - The exposure.
  22592. * @return {Node<vec3>} The tone mapped color.
  22593. */
  22594. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22595. return color.mul( exposure ).clamp();
  22596. } ).setLayout( {
  22597. name: 'linearToneMapping',
  22598. type: 'vec3',
  22599. inputs: [
  22600. { name: 'color', type: 'vec3' },
  22601. { name: 'exposure', type: 'float' }
  22602. ]
  22603. } );
  22604. /**
  22605. * Reinhard tone mapping.
  22606. *
  22607. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22608. *
  22609. * @method
  22610. * @param {Node<vec3>} color - The color that should be tone mapped.
  22611. * @param {Node<float>} exposure - The exposure.
  22612. * @return {Node<vec3>} The tone mapped color.
  22613. */
  22614. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22615. color = color.mul( exposure );
  22616. return color.div( color.add( 1.0 ) ).clamp();
  22617. } ).setLayout( {
  22618. name: 'reinhardToneMapping',
  22619. type: 'vec3',
  22620. inputs: [
  22621. { name: 'color', type: 'vec3' },
  22622. { name: 'exposure', type: 'float' }
  22623. ]
  22624. } );
  22625. /**
  22626. * Cineon tone mapping.
  22627. *
  22628. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22629. *
  22630. * @method
  22631. * @param {Node<vec3>} color - The color that should be tone mapped.
  22632. * @param {Node<float>} exposure - The exposure.
  22633. * @return {Node<vec3>} The tone mapped color.
  22634. */
  22635. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22636. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22637. color = color.mul( exposure );
  22638. color = color.sub( 0.004 ).max( 0.0 );
  22639. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22640. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22641. return a.div( b ).pow( 2.2 );
  22642. } ).setLayout( {
  22643. name: 'cineonToneMapping',
  22644. type: 'vec3',
  22645. inputs: [
  22646. { name: 'color', type: 'vec3' },
  22647. { name: 'exposure', type: 'float' }
  22648. ]
  22649. } );
  22650. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22651. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22652. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22653. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22654. return a.div( b );
  22655. } );
  22656. /**
  22657. * ACESFilmic tone mapping.
  22658. *
  22659. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22660. *
  22661. * @method
  22662. * @param {Node<vec3>} color - The color that should be tone mapped.
  22663. * @param {Node<float>} exposure - The exposure.
  22664. * @return {Node<vec3>} The tone mapped color.
  22665. */
  22666. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22667. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22668. const ACESInputMat = mat3(
  22669. 0.59719, 0.35458, 0.04823,
  22670. 0.07600, 0.90834, 0.01566,
  22671. 0.02840, 0.13383, 0.83777
  22672. );
  22673. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22674. const ACESOutputMat = mat3(
  22675. 1.60475, - 0.53108, - 0.07367,
  22676. - 0.10208, 1.10813, - 0.00605,
  22677. - 0.00327, - 0.07276, 1.07602
  22678. );
  22679. color = color.mul( exposure ).div( 0.6 );
  22680. color = ACESInputMat.mul( color );
  22681. // Apply RRT and ODT
  22682. color = RRTAndODTFit( color );
  22683. color = ACESOutputMat.mul( color );
  22684. // Clamp to [0, 1]
  22685. return color.clamp();
  22686. } ).setLayout( {
  22687. name: 'acesFilmicToneMapping',
  22688. type: 'vec3',
  22689. inputs: [
  22690. { name: 'color', type: 'vec3' },
  22691. { name: 'exposure', type: 'float' }
  22692. ]
  22693. } );
  22694. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  22695. 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 ) );
  22696. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22697. const x = vec3( x_immutable ).toVar();
  22698. const x2 = vec3( x.mul( x ) ).toVar();
  22699. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22700. 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 ) ) ) );
  22701. } );
  22702. /**
  22703. * AgX tone mapping.
  22704. *
  22705. * @method
  22706. * @param {Node<vec3>} color - The color that should be tone mapped.
  22707. * @param {Node<float>} exposure - The exposure.
  22708. * @return {Node<vec3>} The tone mapped color.
  22709. */
  22710. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22711. const colortone = vec3( color ).toVar();
  22712. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22713. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22714. const AgxMinEv = float( - 12.47393 );
  22715. const AgxMaxEv = float( 4.026069 );
  22716. colortone.mulAssign( exposure );
  22717. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22718. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22719. colortone.assign( max$1( colortone, 1e-10 ) );
  22720. colortone.assign( log2( colortone ) );
  22721. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22722. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22723. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22724. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22725. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22726. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22727. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22728. return colortone;
  22729. } ).setLayout( {
  22730. name: 'agxToneMapping',
  22731. type: 'vec3',
  22732. inputs: [
  22733. { name: 'color', type: 'vec3' },
  22734. { name: 'exposure', type: 'float' }
  22735. ]
  22736. } );
  22737. /**
  22738. * Neutral tone mapping.
  22739. *
  22740. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22741. *
  22742. * @method
  22743. * @param {Node<vec3>} color - The color that should be tone mapped.
  22744. * @param {Node<float>} exposure - The exposure.
  22745. * @return {Node<vec3>} The tone mapped color.
  22746. */
  22747. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22748. const StartCompression = float( 0.8 - 0.04 );
  22749. const Desaturation = float( 0.15 );
  22750. color = color.mul( exposure );
  22751. const x = min$1( color.r, min$1( color.g, color.b ) );
  22752. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22753. color.subAssign( offset );
  22754. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22755. If( peak.lessThan( StartCompression ), () => {
  22756. return color;
  22757. } );
  22758. const d = sub( 1, StartCompression );
  22759. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22760. color.mulAssign( newPeak.div( peak ) );
  22761. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22762. return mix( color, vec3( newPeak ), g );
  22763. } ).setLayout( {
  22764. name: 'neutralToneMapping',
  22765. type: 'vec3',
  22766. inputs: [
  22767. { name: 'color', type: 'vec3' },
  22768. { name: 'exposure', type: 'float' }
  22769. ]
  22770. } );
  22771. /** @module CodeNode **/
  22772. /**
  22773. * This class represents native code sections. It is the base
  22774. * class for modules like {@link FunctionNode} which allows to implement
  22775. * functions with native shader languages.
  22776. *
  22777. * @augments Node
  22778. */
  22779. class CodeNode extends Node {
  22780. static get type() {
  22781. return 'CodeNode';
  22782. }
  22783. /**
  22784. * Constructs a new code node.
  22785. *
  22786. * @param {String} [code=''] - The native code.
  22787. * @param {Array<Node>} [includes=[]] - An array of includes.
  22788. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22789. */
  22790. constructor( code = '', includes = [], language = '' ) {
  22791. super( 'code' );
  22792. /**
  22793. * This flag can be used for type testing.
  22794. *
  22795. * @type {Boolean}
  22796. * @readonly
  22797. * @default true
  22798. */
  22799. this.isCodeNode = true;
  22800. /**
  22801. * The native code.
  22802. *
  22803. * @type {String}
  22804. * @default ''
  22805. */
  22806. this.code = code;
  22807. /**
  22808. * An array of includes
  22809. *
  22810. * @type {Array<Node>}
  22811. * @default []
  22812. */
  22813. this.includes = includes;
  22814. /**
  22815. * The used language.
  22816. *
  22817. * @type {('js'|'wgsl'|'glsl')}
  22818. * @default ''
  22819. */
  22820. this.language = language;
  22821. }
  22822. /**
  22823. * The method is overwritten so it always returns `true`.
  22824. *
  22825. * @return {Boolean} Whether this node is global or not.
  22826. */
  22827. isGlobal() {
  22828. return true;
  22829. }
  22830. /**
  22831. * Sets the includes of this code node.
  22832. *
  22833. * @param {Array<Node>} includes - The includes to set.
  22834. * @return {CodeNode} A reference to this node.
  22835. */
  22836. setIncludes( includes ) {
  22837. this.includes = includes;
  22838. return this;
  22839. }
  22840. /**
  22841. * Returns the includes of this code node.
  22842. *
  22843. * @param {NodeBuilder} builder - The current node builder.
  22844. * @return {Array<Node>} The includes.
  22845. */
  22846. getIncludes( /*builder*/ ) {
  22847. return this.includes;
  22848. }
  22849. generate( builder ) {
  22850. const includes = this.getIncludes( builder );
  22851. for ( const include of includes ) {
  22852. include.build( builder );
  22853. }
  22854. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22855. nodeCode.code = this.code;
  22856. return nodeCode.code;
  22857. }
  22858. serialize( data ) {
  22859. super.serialize( data );
  22860. data.code = this.code;
  22861. data.language = this.language;
  22862. }
  22863. deserialize( data ) {
  22864. super.deserialize( data );
  22865. this.code = data.code;
  22866. this.language = data.language;
  22867. }
  22868. }
  22869. /**
  22870. * TSL function for creating a code node.
  22871. *
  22872. * @function
  22873. * @param {String} [code=''] - The native code.
  22874. * @param {Array<Node>} [includes=[]] - An array of includes.
  22875. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22876. * @returns {CodeNode}
  22877. */
  22878. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22879. /**
  22880. * TSL function for creating a JS code node.
  22881. *
  22882. * @function
  22883. * @param {String} src - The native code.
  22884. * @param {Array<Node>} includes - An array of includes.
  22885. * @returns {CodeNode}
  22886. */
  22887. const js = ( src, includes ) => code( src, includes, 'js' );
  22888. /**
  22889. * TSL function for creating a WGSL code node.
  22890. *
  22891. * @function
  22892. * @param {String} src - The native code.
  22893. * @param {Array<Node>} includes - An array of includes.
  22894. * @returns {CodeNode}
  22895. */
  22896. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22897. /**
  22898. * TSL function for creating a GLSL code node.
  22899. *
  22900. * @function
  22901. * @param {String} src - The native code.
  22902. * @param {Array<Node>} includes - An array of includes.
  22903. * @returns {CodeNode}
  22904. */
  22905. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22906. /**
  22907. * This class represents a native shader function. It can be used to implement
  22908. * certain aspects of a node material with native shader code. There are two predefined
  22909. * TSL functions for easier usage.
  22910. *
  22911. * - `wgslFn`: Creates a WGSL function node.
  22912. * - `glslFn`: Creates a GLSL function node.
  22913. *
  22914. * A basic example with one include looks like so:
  22915. *
  22916. * ```js
  22917. * const desaturateWGSLFn = wgslFn( `
  22918. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22919. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22920. * return vec3<f32>( dot( lum, color ) );
  22921. * }`
  22922. *);
  22923. * const someWGSLFn = wgslFn( `
  22924. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22925. * return desaturate( color );
  22926. * }
  22927. * `, [ desaturateWGSLFn ] );
  22928. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22929. *```
  22930. * @augments CodeNode
  22931. */
  22932. class FunctionNode extends CodeNode {
  22933. static get type() {
  22934. return 'FunctionNode';
  22935. }
  22936. /**
  22937. * Constructs a new function node.
  22938. *
  22939. * @param {String} [code=''] - The native code.
  22940. * @param {Array<Node>} [includes=[]] - An array of includes.
  22941. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22942. */
  22943. constructor( code = '', includes = [], language = '' ) {
  22944. super( code, includes, language );
  22945. }
  22946. getNodeType( builder ) {
  22947. return this.getNodeFunction( builder ).type;
  22948. }
  22949. /**
  22950. * Returns the inputs of this function node.
  22951. *
  22952. * @param {NodeBuilder} builder - The current node builder.
  22953. * @return {Array<NodeFunctionInput>} The inputs.
  22954. */
  22955. getInputs( builder ) {
  22956. return this.getNodeFunction( builder ).inputs;
  22957. }
  22958. /**
  22959. * Returns the node function for this function node.
  22960. *
  22961. * @param {NodeBuilder} builder - The current node builder.
  22962. * @return {NodeFunction} The node function.
  22963. */
  22964. getNodeFunction( builder ) {
  22965. const nodeData = builder.getDataFromNode( this );
  22966. let nodeFunction = nodeData.nodeFunction;
  22967. if ( nodeFunction === undefined ) {
  22968. nodeFunction = builder.parser.parseFunction( this.code );
  22969. nodeData.nodeFunction = nodeFunction;
  22970. }
  22971. return nodeFunction;
  22972. }
  22973. generate( builder, output ) {
  22974. super.generate( builder );
  22975. const nodeFunction = this.getNodeFunction( builder );
  22976. const name = nodeFunction.name;
  22977. const type = nodeFunction.type;
  22978. const nodeCode = builder.getCodeFromNode( this, type );
  22979. if ( name !== '' ) {
  22980. // use a custom property name
  22981. nodeCode.name = name;
  22982. }
  22983. const propertyName = builder.getPropertyName( nodeCode );
  22984. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22985. nodeCode.code = code + '\n';
  22986. if ( output === 'property' ) {
  22987. return propertyName;
  22988. } else {
  22989. return builder.format( `${ propertyName }()`, type, output );
  22990. }
  22991. }
  22992. }
  22993. const nativeFn = ( code, includes = [], language = '' ) => {
  22994. for ( let i = 0; i < includes.length; i ++ ) {
  22995. const include = includes[ i ];
  22996. // TSL Function: glslFn, wgslFn
  22997. if ( typeof include === 'function' ) {
  22998. includes[ i ] = include.functionNode;
  22999. }
  23000. }
  23001. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23002. const fn = ( ...params ) => functionNode.call( ...params );
  23003. fn.functionNode = functionNode;
  23004. return fn;
  23005. };
  23006. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23007. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23008. /** @module ScriptableValueNode **/
  23009. /**
  23010. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23011. *
  23012. * @augments Node
  23013. */
  23014. class ScriptableValueNode extends Node {
  23015. static get type() {
  23016. return 'ScriptableValueNode';
  23017. }
  23018. /**
  23019. * Constructs a new scriptable node.
  23020. *
  23021. * @param {Any} [value=null] - The value.
  23022. */
  23023. constructor( value = null ) {
  23024. super();
  23025. /**
  23026. * A reference to the value.
  23027. *
  23028. * @private
  23029. * @default null
  23030. */
  23031. this._value = value;
  23032. /**
  23033. * Depending on the type of `_value`, this property might cache parsed data.
  23034. *
  23035. * @private
  23036. * @default null
  23037. */
  23038. this._cache = null;
  23039. /**
  23040. * If this node represents an input, this property represents the input type.
  23041. *
  23042. * @type {String?}
  23043. * @default null
  23044. */
  23045. this.inputType = null;
  23046. /**
  23047. * If this node represents an output, this property represents the output type.
  23048. *
  23049. * @type {String?}
  23050. * @default null
  23051. */
  23052. this.outputType = null;
  23053. /**
  23054. * An event dispatcher for managing events.
  23055. *
  23056. * @type {EventDispatcher}
  23057. */
  23058. this.events = new EventDispatcher();
  23059. /**
  23060. * This flag can be used for type testing.
  23061. *
  23062. * @type {Boolean}
  23063. * @readonly
  23064. * @default true
  23065. */
  23066. this.isScriptableValueNode = true;
  23067. }
  23068. /**
  23069. * Whether this node represents an output or not.
  23070. *
  23071. * @type {Boolean}
  23072. * @readonly
  23073. * @default true
  23074. */
  23075. get isScriptableOutputNode() {
  23076. return this.outputType !== null;
  23077. }
  23078. set value( val ) {
  23079. if ( this._value === val ) return;
  23080. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23081. URL.revokeObjectURL( this._cache );
  23082. this._cache = null;
  23083. }
  23084. this._value = val;
  23085. this.events.dispatchEvent( { type: 'change' } );
  23086. this.refresh();
  23087. }
  23088. /**
  23089. * The node's value.
  23090. *
  23091. * @type {Any}
  23092. */
  23093. get value() {
  23094. return this._value;
  23095. }
  23096. /**
  23097. * Dispatches the `refresh` event.
  23098. */
  23099. refresh() {
  23100. this.events.dispatchEvent( { type: 'refresh' } );
  23101. }
  23102. /**
  23103. * The `value` property usually represents a node or even binary data in form of array buffers.
  23104. * In this case, this method tries to return the actual value behind the complex type.
  23105. *
  23106. * @return {Any} The value.
  23107. */
  23108. getValue() {
  23109. const value = this.value;
  23110. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23111. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23112. } else if ( value && value.value !== null && value.value !== undefined && (
  23113. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23114. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23115. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23116. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23117. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23118. ( this.inputType === 'Color' && value.value.isColor ) ||
  23119. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23120. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23121. ) ) {
  23122. return value.value;
  23123. }
  23124. return this._cache || value;
  23125. }
  23126. /**
  23127. * Overwritten since the node type is inferred from the value.
  23128. *
  23129. * @param {NodeBuilder} builder - The current node builder.
  23130. * @return {String} The node type.
  23131. */
  23132. getNodeType( builder ) {
  23133. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23134. }
  23135. setup() {
  23136. return this.value && this.value.isNode ? this.value : float();
  23137. }
  23138. serialize( data ) {
  23139. super.serialize( data );
  23140. if ( this.value !== null ) {
  23141. if ( this.inputType === 'ArrayBuffer' ) {
  23142. data.value = arrayBufferToBase64( this.value );
  23143. } else {
  23144. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23145. }
  23146. } else {
  23147. data.value = null;
  23148. }
  23149. data.inputType = this.inputType;
  23150. data.outputType = this.outputType;
  23151. }
  23152. deserialize( data ) {
  23153. super.deserialize( data );
  23154. let value = null;
  23155. if ( data.value !== null ) {
  23156. if ( data.inputType === 'ArrayBuffer' ) {
  23157. value = base64ToArrayBuffer( data.value );
  23158. } else if ( data.inputType === 'Texture' ) {
  23159. value = data.meta.textures[ data.value ];
  23160. } else {
  23161. value = data.meta.nodes[ data.value ] || null;
  23162. }
  23163. }
  23164. this.value = value;
  23165. this.inputType = data.inputType;
  23166. this.outputType = data.outputType;
  23167. }
  23168. }
  23169. /**
  23170. * TSL function for creating a scriptable value node.
  23171. *
  23172. * @function
  23173. * @param {Any} [value=null] - The value.
  23174. * @returns {ScriptableValueNode}
  23175. */
  23176. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23177. /** @module ScriptableNode **/
  23178. /**
  23179. * A Map-like data structure for managing resources of scriptable nodes.
  23180. *
  23181. * @augments Map
  23182. */
  23183. class Resources extends Map {
  23184. get( key, callback = null, ...params ) {
  23185. if ( this.has( key ) ) return super.get( key );
  23186. if ( callback !== null ) {
  23187. const value = callback( ...params );
  23188. this.set( key, value );
  23189. return value;
  23190. }
  23191. }
  23192. }
  23193. class Parameters {
  23194. constructor( scriptableNode ) {
  23195. this.scriptableNode = scriptableNode;
  23196. }
  23197. get parameters() {
  23198. return this.scriptableNode.parameters;
  23199. }
  23200. get layout() {
  23201. return this.scriptableNode.getLayout();
  23202. }
  23203. getInputLayout( id ) {
  23204. return this.scriptableNode.getInputLayout( id );
  23205. }
  23206. get( name ) {
  23207. const param = this.parameters[ name ];
  23208. const value = param ? param.getValue() : null;
  23209. return value;
  23210. }
  23211. }
  23212. /**
  23213. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23214. *
  23215. * @type {Resources}
  23216. */
  23217. const ScriptableNodeResources = new Resources();
  23218. /**
  23219. * This type of node allows to implement nodes with custom scripts. The script
  23220. * section is represented as an instance of `CodeNode` written with JavaScript.
  23221. * The script itself must adhere to a specific structure.
  23222. *
  23223. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23224. * - layout: The layout object defines the script's interface (inputs and outputs).
  23225. *
  23226. * ```js
  23227. * ScriptableNodeResources.set( 'TSL', TSL );
  23228. *
  23229. * const scriptableNode = scriptable( js( `
  23230. * layout = {
  23231. * outputType: 'node',
  23232. * elements: [
  23233. * { name: 'source', inputType: 'node' },
  23234. * ]
  23235. * };
  23236. *
  23237. * const { mul, oscSine } = TSL;
  23238. *
  23239. * function main() {
  23240. * const source = parameters.get( 'source' ) || float();
  23241. * return mul( source, oscSine() ) );
  23242. * }
  23243. *
  23244. * ` ) );
  23245. *
  23246. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23247. *
  23248. * const material = new THREE.MeshBasicNodeMaterial();
  23249. * material.colorNode = scriptableNode;
  23250. * ```
  23251. *
  23252. * @augments Node
  23253. */
  23254. class ScriptableNode extends Node {
  23255. static get type() {
  23256. return 'ScriptableNode';
  23257. }
  23258. /**
  23259. * Constructs a new scriptable node.
  23260. *
  23261. * @param {CodeNode?} [codeNode=null] - The code node.
  23262. * @param {Object} [parameters={}] - The parameters definition.
  23263. */
  23264. constructor( codeNode = null, parameters = {} ) {
  23265. super();
  23266. /**
  23267. * The code node.
  23268. *
  23269. * @type {CodeNode?}
  23270. * @default null
  23271. */
  23272. this.codeNode = codeNode;
  23273. /**
  23274. * The parameters definition.
  23275. *
  23276. * @type {Object}
  23277. * @default {}
  23278. */
  23279. this.parameters = parameters;
  23280. this._local = new Resources();
  23281. this._output = scriptableValue();
  23282. this._outputs = {};
  23283. this._source = this.source;
  23284. this._method = null;
  23285. this._object = null;
  23286. this._value = null;
  23287. this._needsOutputUpdate = true;
  23288. this.onRefresh = this.onRefresh.bind( this );
  23289. /**
  23290. * This flag can be used for type testing.
  23291. *
  23292. * @type {Boolean}
  23293. * @readonly
  23294. * @default true
  23295. */
  23296. this.isScriptableNode = true;
  23297. }
  23298. /**
  23299. * The source code of the scriptable node.
  23300. *
  23301. * @type {String}
  23302. */
  23303. get source() {
  23304. return this.codeNode ? this.codeNode.code : '';
  23305. }
  23306. /**
  23307. * Sets the reference of a local script variable.
  23308. *
  23309. * @param {String} name - The variable name.
  23310. * @param {Object} value - The reference to set.
  23311. * @return {Resources} The resource map
  23312. */
  23313. setLocal( name, value ) {
  23314. return this._local.set( name, value );
  23315. }
  23316. /**
  23317. * Gets the value of a local script variable.
  23318. *
  23319. * @param {String} name - The variable name.
  23320. * @return {Object} The value.
  23321. */
  23322. getLocal( name ) {
  23323. return this._local.get( name );
  23324. }
  23325. /**
  23326. * Event listener for the `refresh` event.
  23327. */
  23328. onRefresh() {
  23329. this._refresh();
  23330. }
  23331. /**
  23332. * Returns an input from the layout with the given id/name.
  23333. *
  23334. * @param {String} id - The id/name of the input.
  23335. * @return {Object} The element entry.
  23336. */
  23337. getInputLayout( id ) {
  23338. for ( const element of this.getLayout() ) {
  23339. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23340. return element;
  23341. }
  23342. }
  23343. }
  23344. /**
  23345. * Returns an output from the layout with the given id/name.
  23346. *
  23347. * @param {String} id - The id/name of the output.
  23348. * @return {Object} The element entry.
  23349. */
  23350. getOutputLayout( id ) {
  23351. for ( const element of this.getLayout() ) {
  23352. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23353. return element;
  23354. }
  23355. }
  23356. }
  23357. /**
  23358. * Defines a script output for the given name and value.
  23359. *
  23360. * @param {String} name - The name of the output.
  23361. * @param {Node} value - The node value.
  23362. * @return {ScriptableNode} A reference to this node.
  23363. */
  23364. setOutput( name, value ) {
  23365. const outputs = this._outputs;
  23366. if ( outputs[ name ] === undefined ) {
  23367. outputs[ name ] = scriptableValue( value );
  23368. } else {
  23369. outputs[ name ].value = value;
  23370. }
  23371. return this;
  23372. }
  23373. /**
  23374. * Returns a script output for the given name.
  23375. *
  23376. * @param {String} name - The name of the output.
  23377. * @return {ScriptableValueNode} The node value.
  23378. */
  23379. getOutput( name ) {
  23380. return this._outputs[ name ];
  23381. }
  23382. /**
  23383. * Returns a parameter for the given name
  23384. *
  23385. * @param {String} name - The name of the parameter.
  23386. * @return {ScriptableValueNode} The node value.
  23387. */
  23388. getParameter( name ) {
  23389. return this.parameters[ name ];
  23390. }
  23391. /**
  23392. * Sets a value for the given parameter name.
  23393. *
  23394. * @param {String} name - The parameter name.
  23395. * @param {Any} value - The parameter value.
  23396. * @return {ScriptableNode} A reference to this node.
  23397. */
  23398. setParameter( name, value ) {
  23399. const parameters = this.parameters;
  23400. if ( value && value.isScriptableNode ) {
  23401. this.deleteParameter( name );
  23402. parameters[ name ] = value;
  23403. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23404. } else if ( value && value.isScriptableValueNode ) {
  23405. this.deleteParameter( name );
  23406. parameters[ name ] = value;
  23407. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23408. } else if ( parameters[ name ] === undefined ) {
  23409. parameters[ name ] = scriptableValue( value );
  23410. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23411. } else {
  23412. parameters[ name ].value = value;
  23413. }
  23414. return this;
  23415. }
  23416. /**
  23417. * Returns the value of this node which is the value of
  23418. * the default output.
  23419. *
  23420. * @return {Node} The value.
  23421. */
  23422. getValue() {
  23423. return this.getDefaultOutput().getValue();
  23424. }
  23425. /**
  23426. * Deletes a parameter from the script.
  23427. *
  23428. * @param {String} name - The parameter to remove.
  23429. * @return {ScriptableNode} A reference to this node.
  23430. */
  23431. deleteParameter( name ) {
  23432. let valueNode = this.parameters[ name ];
  23433. if ( valueNode ) {
  23434. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23435. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23436. }
  23437. return this;
  23438. }
  23439. /**
  23440. * Deletes all parameters from the script.
  23441. *
  23442. * @return {ScriptableNode} A reference to this node.
  23443. */
  23444. clearParameters() {
  23445. for ( const name of Object.keys( this.parameters ) ) {
  23446. this.deleteParameter( name );
  23447. }
  23448. this.needsUpdate = true;
  23449. return this;
  23450. }
  23451. /**
  23452. * Calls a function from the script.
  23453. *
  23454. * @param {String} name - The function name.
  23455. * @param {...Any} params - A list of parameters.
  23456. * @return {Any} The result of the function call.
  23457. */
  23458. call( name, ...params ) {
  23459. const object = this.getObject();
  23460. const method = object[ name ];
  23461. if ( typeof method === 'function' ) {
  23462. return method( ...params );
  23463. }
  23464. }
  23465. /**
  23466. * Asynchronously calls a function from the script.
  23467. *
  23468. * @param {String} name - The function name.
  23469. * @param {...Any} params - A list of parameters.
  23470. * @return {Promise<Any>} The result of the function call.
  23471. */
  23472. async callAsync( name, ...params ) {
  23473. const object = this.getObject();
  23474. const method = object[ name ];
  23475. if ( typeof method === 'function' ) {
  23476. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23477. }
  23478. }
  23479. /**
  23480. * Overwritten since the node types is inferred from the script's output.
  23481. *
  23482. * @param {NodeBuilder} builder - The current node builder
  23483. * @return {String} The node type.
  23484. */
  23485. getNodeType( builder ) {
  23486. return this.getDefaultOutputNode().getNodeType( builder );
  23487. }
  23488. /**
  23489. * Refreshes the script node.
  23490. *
  23491. * @param {String?} [output=null] - An optional output.
  23492. */
  23493. refresh( output = null ) {
  23494. if ( output !== null ) {
  23495. this.getOutput( output ).refresh();
  23496. } else {
  23497. this._refresh();
  23498. }
  23499. }
  23500. /**
  23501. * Returns an object representation of the script.
  23502. *
  23503. * @return {Object} The result object.
  23504. */
  23505. getObject() {
  23506. if ( this.needsUpdate ) this.dispose();
  23507. if ( this._object !== null ) return this._object;
  23508. //
  23509. const refresh = () => this.refresh();
  23510. const setOutput = ( id, value ) => this.setOutput( id, value );
  23511. const parameters = new Parameters( this );
  23512. const THREE = ScriptableNodeResources.get( 'THREE' );
  23513. const TSL = ScriptableNodeResources.get( 'TSL' );
  23514. const method = this.getMethod();
  23515. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23516. this._object = method( ...params );
  23517. const layout = this._object.layout;
  23518. if ( layout ) {
  23519. if ( layout.cache === false ) {
  23520. this._local.clear();
  23521. }
  23522. // default output
  23523. this._output.outputType = layout.outputType || null;
  23524. if ( Array.isArray( layout.elements ) ) {
  23525. for ( const element of layout.elements ) {
  23526. const id = element.id || element.name;
  23527. if ( element.inputType ) {
  23528. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23529. this.getParameter( id ).inputType = element.inputType;
  23530. }
  23531. if ( element.outputType ) {
  23532. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23533. this.getOutput( id ).outputType = element.outputType;
  23534. }
  23535. }
  23536. }
  23537. }
  23538. return this._object;
  23539. }
  23540. deserialize( data ) {
  23541. super.deserialize( data );
  23542. for ( const name in this.parameters ) {
  23543. let valueNode = this.parameters[ name ];
  23544. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23545. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23546. }
  23547. }
  23548. /**
  23549. * Returns the layout of the script.
  23550. *
  23551. * @return {Object} The script's layout.
  23552. */
  23553. getLayout() {
  23554. return this.getObject().layout;
  23555. }
  23556. /**
  23557. * Returns default node output of the script.
  23558. *
  23559. * @return {Node} The default node output.
  23560. */
  23561. getDefaultOutputNode() {
  23562. const output = this.getDefaultOutput().value;
  23563. if ( output && output.isNode ) {
  23564. return output;
  23565. }
  23566. return float();
  23567. }
  23568. /**
  23569. * Returns default output of the script.
  23570. *
  23571. * @return {ScriptableValueNode} The default output.
  23572. */
  23573. getDefaultOutput() {
  23574. return this._exec()._output;
  23575. }
  23576. /**
  23577. * Returns a function created from the node's script.
  23578. *
  23579. * @return {Function} The function representing the node's code.
  23580. */
  23581. getMethod() {
  23582. if ( this.needsUpdate ) this.dispose();
  23583. if ( this._method !== null ) return this._method;
  23584. //
  23585. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23586. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23587. const properties = interfaceProps.join( ', ' );
  23588. const declarations = 'var ' + properties + '; var output = {};\n';
  23589. const returns = '\nreturn { ...output, ' + properties + ' };';
  23590. const code = declarations + this.codeNode.code + returns;
  23591. //
  23592. this._method = new Function( ...parametersProps, code );
  23593. return this._method;
  23594. }
  23595. /**
  23596. * Frees all internal resources.
  23597. */
  23598. dispose() {
  23599. if ( this._method === null ) return;
  23600. if ( this._object && typeof this._object.dispose === 'function' ) {
  23601. this._object.dispose();
  23602. }
  23603. this._method = null;
  23604. this._object = null;
  23605. this._source = null;
  23606. this._value = null;
  23607. this._needsOutputUpdate = true;
  23608. this._output.value = null;
  23609. this._outputs = {};
  23610. }
  23611. setup() {
  23612. return this.getDefaultOutputNode();
  23613. }
  23614. getCacheKey( force ) {
  23615. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23616. for ( const param in this.parameters ) {
  23617. values.push( this.parameters[ param ].getCacheKey( force ) );
  23618. }
  23619. return hashArray( values );
  23620. }
  23621. set needsUpdate( value ) {
  23622. if ( value === true ) this.dispose();
  23623. }
  23624. get needsUpdate() {
  23625. return this.source !== this._source;
  23626. }
  23627. /**
  23628. * Executes the `main` function of the script.
  23629. *
  23630. * @private
  23631. * @return {ScriptableNode} A reference to this node.
  23632. */
  23633. _exec() {
  23634. if ( this.codeNode === null ) return this;
  23635. if ( this._needsOutputUpdate === true ) {
  23636. this._value = this.call( 'main' );
  23637. this._needsOutputUpdate = false;
  23638. }
  23639. this._output.value = this._value;
  23640. return this;
  23641. }
  23642. /**
  23643. * Executes the refresh.
  23644. *
  23645. * @private
  23646. */
  23647. _refresh() {
  23648. this.needsUpdate = true;
  23649. this._exec();
  23650. this._output.refresh();
  23651. }
  23652. }
  23653. /**
  23654. * TSL function for creating a scriptable node.
  23655. *
  23656. * @function
  23657. * @param {CodeNode?} [codeNode=null] - The code node.
  23658. * @param {Object} [parameters={}] - The parameters definition.
  23659. * @returns {ScriptableNode}
  23660. */
  23661. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23662. /** @module Fog **/
  23663. /**
  23664. * Returns a node that represents the `z` coordinate in view space
  23665. * for the current fragment. It's a different representation of the
  23666. * default depth value.
  23667. *
  23668. * This value can be part of a computation that defines how the fog
  23669. * density increases when moving away from the camera.
  23670. *
  23671. * @param {NodeBuilder} builder - The current node builder.
  23672. * @return {Node} The viewZ node.
  23673. */
  23674. function getViewZNode( builder ) {
  23675. let viewZ;
  23676. const getViewZ = builder.context.getViewZ;
  23677. if ( getViewZ !== undefined ) {
  23678. viewZ = getViewZ( this );
  23679. }
  23680. return ( viewZ || positionView.z ).negate();
  23681. }
  23682. /**
  23683. * Constructs a new range factor node.
  23684. *
  23685. * @function
  23686. * @param {Node} near - Defines the near value.
  23687. * @param {Node} far - Defines the far value.
  23688. */
  23689. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23690. const viewZ = getViewZNode( builder );
  23691. return smoothstep( near, far, viewZ );
  23692. } );
  23693. /**
  23694. * Represents an exponential squared fog. This type of fog gives
  23695. * a clear view near the camera and a faster than exponentially
  23696. * densening fog farther from the camera.
  23697. *
  23698. * @function
  23699. * @param {Node} density - Defines the fog density.
  23700. */
  23701. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23702. const viewZ = getViewZNode( builder );
  23703. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23704. } );
  23705. /**
  23706. * This class can be used to configure a fog for the scene.
  23707. * Nodes of this type are assigned to `Scene.fogNode`.
  23708. *
  23709. * @function
  23710. * @param {Node} color - Defines the color of the fog.
  23711. * @param {Node} factor - Defines how the fog is factored in the scene.
  23712. */
  23713. const fog = Fn( ( [ color, factor ] ) => {
  23714. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23715. } );
  23716. // Deprecated
  23717. /**
  23718. * @function
  23719. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23720. *
  23721. * @param {Node} color
  23722. * @param {Node} near
  23723. * @param {Node} far
  23724. * @returns {Function}
  23725. */
  23726. function rangeFog( color, near, far ) { // @deprecated, r171
  23727. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23728. return fog( color, rangeFogFactor( near, far ) );
  23729. }
  23730. /**
  23731. * @function
  23732. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23733. *
  23734. * @param {Node} color
  23735. * @param {Node} density
  23736. * @returns {Function}
  23737. */
  23738. function densityFog( color, density ) { // @deprecated, r171
  23739. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23740. return fog( color, densityFogFactor( density ) );
  23741. }
  23742. /** @module RangeNode **/
  23743. let min = null;
  23744. let max = null;
  23745. /**
  23746. * `RangeNode` generates random instanced attribute data in a defined range.
  23747. * An exemplary use case for this utility node is to generate random per-instance
  23748. * colors:
  23749. * ```js
  23750. * const material = new MeshBasicNodeMaterial();
  23751. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23752. * const mesh = new InstancedMesh( geometry, material, count );
  23753. * ```
  23754. * @augments Node
  23755. */
  23756. class RangeNode extends Node {
  23757. static get type() {
  23758. return 'RangeNode';
  23759. }
  23760. /**
  23761. * Constructs a new range node.
  23762. *
  23763. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23764. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23765. */
  23766. constructor( minNode = float(), maxNode = float() ) {
  23767. super();
  23768. /**
  23769. * A node defining the lower bound of the range.
  23770. *
  23771. * @type {Node<any>}
  23772. * @default float()
  23773. */
  23774. this.minNode = minNode;
  23775. /**
  23776. * A node defining the upper bound of the range.
  23777. *
  23778. * @type {Node<any>}
  23779. * @default float()
  23780. */
  23781. this.maxNode = maxNode;
  23782. }
  23783. /**
  23784. * Returns the vector length which is computed based on the range definition.
  23785. *
  23786. * @param {NodeBuilder} builder - The current node builder.
  23787. * @return {Number} The vector length.
  23788. */
  23789. getVectorLength( builder ) {
  23790. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23791. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23792. return minLength > maxLength ? minLength : maxLength;
  23793. }
  23794. /**
  23795. * This method is overwritten since the node type is inferred from range definition.
  23796. *
  23797. * @param {NodeBuilder} builder - The current node builder.
  23798. * @return {String} The node type.
  23799. */
  23800. getNodeType( builder ) {
  23801. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23802. }
  23803. setup( builder ) {
  23804. const object = builder.object;
  23805. let output = null;
  23806. if ( object.count > 1 ) {
  23807. const minValue = this.minNode.value;
  23808. const maxValue = this.maxNode.value;
  23809. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23810. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23811. min = min || new Vector4();
  23812. max = max || new Vector4();
  23813. min.setScalar( 0 );
  23814. max.setScalar( 0 );
  23815. if ( minLength === 1 ) min.setScalar( minValue );
  23816. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23817. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23818. if ( maxLength === 1 ) max.setScalar( maxValue );
  23819. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23820. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23821. const stride = 4;
  23822. const length = stride * object.count;
  23823. const array = new Float32Array( length );
  23824. for ( let i = 0; i < length; i ++ ) {
  23825. const index = i % stride;
  23826. const minElementValue = min.getComponent( index );
  23827. const maxElementValue = max.getComponent( index );
  23828. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23829. }
  23830. const nodeType = this.getNodeType( builder );
  23831. if ( object.count <= 4096 ) {
  23832. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23833. } else {
  23834. // TODO: Improve anonymous buffer attribute creation removing this part
  23835. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23836. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23837. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23838. }
  23839. } else {
  23840. output = float( 0 );
  23841. }
  23842. return output;
  23843. }
  23844. }
  23845. /**
  23846. * TSL function for creating a range node.
  23847. *
  23848. * @function
  23849. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23850. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23851. * @returns {RangeNode}
  23852. */
  23853. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23854. /** @module ComputeBuiltinNode **/
  23855. /**
  23856. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23857. * about the currently running dispatch and/or the device it is running on.
  23858. *
  23859. * This node can only be used with a WebGPU backend.
  23860. *
  23861. * @augments Node
  23862. */
  23863. class ComputeBuiltinNode extends Node {
  23864. static get type() {
  23865. return 'ComputeBuiltinNode';
  23866. }
  23867. /**
  23868. * Constructs a new compute builtin node.
  23869. *
  23870. * @param {String} builtinName - The built-in name.
  23871. * @param {String} nodeType - The node type.
  23872. */
  23873. constructor( builtinName, nodeType ) {
  23874. super( nodeType );
  23875. /**
  23876. * The built-in name.
  23877. *
  23878. * @private
  23879. * @type {String}
  23880. */
  23881. this._builtinName = builtinName;
  23882. }
  23883. /**
  23884. * This method is overwritten since hash is derived from the built-in name.
  23885. *
  23886. * @param {NodeBuilder} builder - The current node builder.
  23887. * @return {String} The hash.
  23888. */
  23889. getHash( builder ) {
  23890. return this.getBuiltinName( builder );
  23891. }
  23892. /**
  23893. * This method is overwritten since the node type is simply derived from `nodeType`..
  23894. *
  23895. * @param {NodeBuilder} builder - The current node builder.
  23896. * @return {String} The node type.
  23897. */
  23898. getNodeType( /*builder*/ ) {
  23899. return this.nodeType;
  23900. }
  23901. /**
  23902. * Sets the builtin name.
  23903. *
  23904. * @param {String} builtinName - The built-in name.
  23905. * @return {ComputeBuiltinNode} A reference to this node.
  23906. */
  23907. setBuiltinName( builtinName ) {
  23908. this._builtinName = builtinName;
  23909. return this;
  23910. }
  23911. /**
  23912. * Returns the builtin name.
  23913. *
  23914. * @param {NodeBuilder} builder - The current node builder.
  23915. * @return {String} The builtin name.
  23916. */
  23917. getBuiltinName( /*builder*/ ) {
  23918. return this._builtinName;
  23919. }
  23920. /**
  23921. * Whether the current node builder has the builtin or not.
  23922. *
  23923. * @param {NodeBuilder} builder - The current node builder.
  23924. */
  23925. hasBuiltin( builder ) {
  23926. builder.hasBuiltin( this._builtinName );
  23927. }
  23928. generate( builder, output ) {
  23929. const builtinName = this.getBuiltinName( builder );
  23930. const nodeType = this.getNodeType( builder );
  23931. if ( builder.shaderStage === 'compute' ) {
  23932. return builder.format( builtinName, nodeType, output );
  23933. } else {
  23934. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23935. return builder.generateConst( nodeType );
  23936. }
  23937. }
  23938. serialize( data ) {
  23939. super.serialize( data );
  23940. data.global = this.global;
  23941. data._builtinName = this._builtinName;
  23942. }
  23943. deserialize( data ) {
  23944. super.deserialize( data );
  23945. this.global = data.global;
  23946. this._builtinName = data._builtinName;
  23947. }
  23948. }
  23949. /**
  23950. * TSL function for creating a compute builtin node.
  23951. *
  23952. * @function
  23953. * @param {String} name - The built-in name.
  23954. * @param {String} nodeType - The node type.
  23955. * @returns {ComputeBuiltinNode}
  23956. */
  23957. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23958. /**
  23959. * TSL function for creating a `numWorkgroups` builtin node.
  23960. * Represents the number of workgroups dispatched by the compute shader.
  23961. * ```js
  23962. * // Run 512 invocations/threads with a workgroup size of 128.
  23963. * const computeFn = Fn(() => {
  23964. *
  23965. * // numWorkgroups.x = 4
  23966. * storageBuffer.element(0).assign(numWorkgroups.x)
  23967. *
  23968. * })().compute(512, [128]);
  23969. *
  23970. * // Run 512 invocations/threads with the default workgroup size of 64.
  23971. * const computeFn = Fn(() => {
  23972. *
  23973. * // numWorkgroups.x = 8
  23974. * storageBuffer.element(0).assign(numWorkgroups.x)
  23975. *
  23976. * })().compute(512);
  23977. * ```
  23978. *
  23979. * @function
  23980. * @returns {ComputeBuiltinNode<uvec3>}
  23981. */
  23982. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23983. /**
  23984. * TSL function for creating a `workgroupId` builtin node.
  23985. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23986. * ```js
  23987. * // Execute 12 compute threads with a workgroup size of 3.
  23988. * const computeFn = Fn( () => {
  23989. *
  23990. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23991. *
  23992. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23993. *
  23994. * } ).Else( () => {
  23995. *
  23996. * storageBuffer.element( instanceIndex ).assign( 0 );
  23997. *
  23998. * } );
  23999. *
  24000. * } )().compute( 12, [ 3 ] );
  24001. *
  24002. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24003. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24004. * ```
  24005. *
  24006. * @function
  24007. * @returns {ComputeBuiltinNode<uvec3>}
  24008. */
  24009. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24010. /**
  24011. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24012. * representation of the current invocation's position within a 3D global grid.
  24013. *
  24014. * @function
  24015. * @returns {ComputeBuiltinNode<uvec3>}
  24016. */
  24017. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24018. /**
  24019. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24020. * representation of the current invocation's position within a 3D workgroup grid.
  24021. *
  24022. * @function
  24023. * @returns {ComputeBuiltinNode<uvec3>}
  24024. */
  24025. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24026. /**
  24027. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24028. * that exposes the size of the current invocation's subgroup.
  24029. *
  24030. * @function
  24031. * @returns {ComputeBuiltinNode<uint>}
  24032. */
  24033. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24034. /** @module BarrierNode **/
  24035. /**
  24036. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24037. *
  24038. * This node can only be used with a WebGPU backend.
  24039. *
  24040. * @augments Node
  24041. */
  24042. class BarrierNode extends Node {
  24043. /**
  24044. * Constructs a new barrier node.
  24045. *
  24046. * @param {String} scope - The scope defines the behavior of the node.
  24047. */
  24048. constructor( scope ) {
  24049. super();
  24050. this.scope = scope;
  24051. }
  24052. generate( builder ) {
  24053. const { scope } = this;
  24054. const { renderer } = builder;
  24055. if ( renderer.backend.isWebGLBackend === true ) {
  24056. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24057. } else {
  24058. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24059. }
  24060. }
  24061. }
  24062. /**
  24063. * TSL function for creating a barrier node.
  24064. *
  24065. * @function
  24066. * @param {String} scope - The scope defines the behavior of the node..
  24067. * @returns {BarrierNode}
  24068. */
  24069. const barrier = nodeProxy( BarrierNode );
  24070. /**
  24071. * TSL function for creating a workgroup barrier. All compute shader
  24072. * invocations must wait for each invocation within a workgroup to
  24073. * complete before the barrier can be surpassed.
  24074. *
  24075. * @function
  24076. * @returns {BarrierNode}
  24077. */
  24078. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24079. /**
  24080. * TSL function for creating a storage barrier. All invocations must
  24081. * wait for each access to variables within the 'storage' address space
  24082. * to complete before the barrier can be passed.
  24083. *
  24084. * @function
  24085. * @returns {BarrierNode}
  24086. */
  24087. const storageBarrier = () => barrier( 'storage' ).append();
  24088. /**
  24089. * TSL function for creating a texture barrier. All invocations must
  24090. * wait for each access to variables within the 'texture' address space
  24091. * to complete before the barrier can be passed.
  24092. *
  24093. * @function
  24094. * @returns {BarrierNode}
  24095. */
  24096. const textureBarrier = () => barrier( 'texture' ).append();
  24097. /** @module WorkgroupInfoNode **/
  24098. /**
  24099. * Represents an element of a 'workgroup' scoped buffer.
  24100. *
  24101. * @augments ArrayElementNode
  24102. */
  24103. class WorkgroupInfoElementNode extends ArrayElementNode {
  24104. /**
  24105. * Constructs a new workgroup info element node.
  24106. *
  24107. * @param {Node} workgroupInfoNode - The workgroup info node.
  24108. * @param {Node} indexNode - The index node that defines the element access.
  24109. */
  24110. constructor( workgroupInfoNode, indexNode ) {
  24111. super( workgroupInfoNode, indexNode );
  24112. /**
  24113. * This flag can be used for type testing.
  24114. *
  24115. * @type {Boolean}
  24116. * @readonly
  24117. * @default true
  24118. */
  24119. this.isWorkgroupInfoElementNode = true;
  24120. }
  24121. generate( builder, output ) {
  24122. let snippet;
  24123. const isAssignContext = builder.context.assign;
  24124. snippet = super.generate( builder );
  24125. if ( isAssignContext !== true ) {
  24126. const type = this.getNodeType( builder );
  24127. snippet = builder.format( snippet, type, output );
  24128. }
  24129. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24130. return snippet;
  24131. }
  24132. }
  24133. /**
  24134. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24135. * context of a compute shader. Typically, workgroup scoped buffers are
  24136. * created to hold data that is transferred from a global storage scope into
  24137. * a local workgroup scope. For invocations within a workgroup, data
  24138. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24139. * than similar access operations on globally accessible storage buffers.
  24140. *
  24141. * This node can only be used with a WebGPU backend.
  24142. *
  24143. * @augments Node
  24144. */
  24145. class WorkgroupInfoNode extends Node {
  24146. /**
  24147. * Constructs a new buffer scoped to type scope.
  24148. *
  24149. * @param {String} scope - TODO.
  24150. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24151. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24152. */
  24153. constructor( scope, bufferType, bufferCount = 0 ) {
  24154. super( bufferType );
  24155. /**
  24156. * The buffer type.
  24157. *
  24158. * @type {String}
  24159. */
  24160. this.bufferType = bufferType;
  24161. /**
  24162. * The buffer count.
  24163. *
  24164. * @type {Number}
  24165. * @default 0
  24166. */
  24167. this.bufferCount = bufferCount;
  24168. /**
  24169. * This flag can be used for type testing.
  24170. *
  24171. * @type {Boolean}
  24172. * @readonly
  24173. * @default true
  24174. */
  24175. this.isWorkgroupInfoNode = true;
  24176. /**
  24177. * The data type of the array buffer.
  24178. *
  24179. * @type {String}
  24180. */
  24181. this.elementType = bufferType;
  24182. /**
  24183. * TODO.
  24184. *
  24185. * @type {String}
  24186. */
  24187. this.scope = scope;
  24188. }
  24189. /**
  24190. * Sets the name/label of this node.
  24191. *
  24192. * @param {String} name - The name to set.
  24193. * @return {WorkgroupInfoNode} A reference to this node.
  24194. */
  24195. label( name ) {
  24196. this.name = name;
  24197. return this;
  24198. }
  24199. /**
  24200. * Sets the scope of this node.
  24201. *
  24202. * @param {String} scope - The scope to set.
  24203. * @return {WorkgroupInfoNode} A reference to this node.
  24204. */
  24205. setScope( scope ) {
  24206. this.scope = scope;
  24207. return this;
  24208. }
  24209. /**
  24210. * The data type of the array buffer.
  24211. *
  24212. * @return {String} The element type.
  24213. */
  24214. getElementType() {
  24215. return this.elementType;
  24216. }
  24217. /**
  24218. * Overwrites the default implementation since the input type
  24219. * is inferred from the scope.
  24220. *
  24221. * @param {NodeBuilder} builder - The current node builder.
  24222. * @return {String} The input type.
  24223. */
  24224. getInputType( /*builder*/ ) {
  24225. return `${this.scope}Array`;
  24226. }
  24227. /**
  24228. * This method can be used to access elements via an index node.
  24229. *
  24230. * @param {IndexNode} indexNode - indexNode.
  24231. * @return {WorkgroupInfoElementNode} A reference to an element.
  24232. */
  24233. element( indexNode ) {
  24234. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24235. }
  24236. generate( builder ) {
  24237. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24238. }
  24239. }
  24240. /**
  24241. * TSL function for creating a workgroup info node.
  24242. * Creates a new 'workgroup' scoped array buffer.
  24243. *
  24244. * @function
  24245. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24246. * @param {Number} [count=0] - The number of elements in the buffer.
  24247. * @returns {WorkgroupInfoNode}
  24248. */
  24249. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24250. /** @module AtomicFunctionNode **/
  24251. /**
  24252. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24253. * within a shader. In an atomic function, any modification to an atomic variable will
  24254. * occur as an indivisible step with a defined order relative to other modifications.
  24255. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24256. * atomic operations will not interfere with each other.
  24257. *
  24258. * This node can only be used with a WebGPU backend.
  24259. *
  24260. * @augments TempNode
  24261. */
  24262. class AtomicFunctionNode extends TempNode {
  24263. static get type() {
  24264. return 'AtomicFunctionNode';
  24265. }
  24266. /**
  24267. * Constructs a new atomic function node.
  24268. *
  24269. * @param {String} method - The signature of the atomic function to construct.
  24270. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24271. * @param {Node} valueNode - The value that mutates the atomic variable.
  24272. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24273. */
  24274. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24275. super( 'uint' );
  24276. /**
  24277. * The signature of the atomic function to construct.
  24278. *
  24279. * @type {String}
  24280. */
  24281. this.method = method;
  24282. /**
  24283. * An atomic variable or element of an atomic buffer.
  24284. *
  24285. * @type {Node}
  24286. */
  24287. this.pointerNode = pointerNode;
  24288. /**
  24289. * A value that modifies the atomic variable.
  24290. *
  24291. * @type {Node}
  24292. */
  24293. this.valueNode = valueNode;
  24294. /**
  24295. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24296. *
  24297. * @type {Node?}
  24298. * @default null
  24299. */
  24300. this.storeNode = storeNode;
  24301. }
  24302. /**
  24303. * Overwrites the default implementation to return the type of
  24304. * the pointer node.
  24305. *
  24306. * @param {NodeBuilder} builder - The current node builder.
  24307. * @return {String} The input type.
  24308. */
  24309. getInputType( builder ) {
  24310. return this.pointerNode.getNodeType( builder );
  24311. }
  24312. /**
  24313. * Overwritten since the node type is inferred from the input type.
  24314. *
  24315. * @param {NodeBuilder} builder - The current node builder.
  24316. * @return {String} The node type.
  24317. */
  24318. getNodeType( builder ) {
  24319. return this.getInputType( builder );
  24320. }
  24321. generate( builder ) {
  24322. const method = this.method;
  24323. const type = this.getNodeType( builder );
  24324. const inputType = this.getInputType( builder );
  24325. const a = this.pointerNode;
  24326. const b = this.valueNode;
  24327. const params = [];
  24328. params.push( `&${ a.build( builder, inputType ) }` );
  24329. params.push( b.build( builder, inputType ) );
  24330. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24331. if ( this.storeNode !== null ) {
  24332. const varSnippet = this.storeNode.build( builder, inputType );
  24333. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24334. } else {
  24335. builder.addLineFlowCode( methodSnippet, this );
  24336. }
  24337. }
  24338. }
  24339. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24340. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24341. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24342. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24343. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24344. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24345. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24346. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24347. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24348. /**
  24349. * TSL function for creating an atomic function node.
  24350. *
  24351. * @function
  24352. * @param {String} method - The signature of the atomic function to construct.
  24353. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24354. * @param {Node} valueNode - The value that mutates the atomic variable.
  24355. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24356. * @returns {AtomicFunctionNode}
  24357. */
  24358. const atomicNode = nodeProxy( AtomicFunctionNode );
  24359. /**
  24360. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  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 atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24370. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24371. node.append();
  24372. return node;
  24373. };
  24374. /**
  24375. * Stores a value in the atomic variable.
  24376. *
  24377. * @function
  24378. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24379. * @param {Node} valueNode - The value that mutates the atomic variable.
  24380. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24381. * @returns {AtomicFunctionNode}
  24382. */
  24383. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24384. /**
  24385. * Increments the value stored in the atomic variable.
  24386. *
  24387. * @function
  24388. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24389. * @param {Node} valueNode - The value that mutates the atomic variable.
  24390. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24391. * @returns {AtomicFunctionNode}
  24392. */
  24393. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24394. /**
  24395. * Decrements the value stored in the atomic variable.
  24396. *
  24397. * @function
  24398. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24399. * @param {Node} valueNode - The value that mutates the atomic variable.
  24400. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24401. * @returns {AtomicFunctionNode}
  24402. */
  24403. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24404. /**
  24405. * Stores in an atomic variable the maximum between its current value and a parameter.
  24406. *
  24407. * @function
  24408. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24409. * @param {Node} valueNode - The value that mutates the atomic variable.
  24410. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24411. * @returns {AtomicFunctionNode}
  24412. */
  24413. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24414. /**
  24415. * Stores in an atomic variable the minimum between its current value and a parameter.
  24416. *
  24417. * @function
  24418. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24419. * @param {Node} valueNode - The value that mutates the atomic variable.
  24420. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24421. * @returns {AtomicFunctionNode}
  24422. */
  24423. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24424. /**
  24425. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24426. *
  24427. * @function
  24428. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24429. * @param {Node} valueNode - The value that mutates the atomic variable.
  24430. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24431. * @returns {AtomicFunctionNode}
  24432. */
  24433. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24434. /**
  24435. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24436. *
  24437. * @function
  24438. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24439. * @param {Node} valueNode - The value that mutates the atomic variable.
  24440. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24441. * @returns {AtomicFunctionNode}
  24442. */
  24443. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24444. /**
  24445. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24446. *
  24447. * @function
  24448. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24449. * @param {Node} valueNode - The value that mutates the atomic variable.
  24450. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24451. * @returns {AtomicFunctionNode}
  24452. */
  24453. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24454. /** @module Lights **/
  24455. let uniformsLib;
  24456. function getLightData( light ) {
  24457. uniformsLib = uniformsLib || new WeakMap();
  24458. let uniforms = uniformsLib.get( light );
  24459. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24460. return uniforms;
  24461. }
  24462. /**
  24463. * TSL function for getting a shadow matrix uniform node for the given light.
  24464. *
  24465. * @function
  24466. * @param {Light} light -The light source.
  24467. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24468. */
  24469. function lightShadowMatrix( light ) {
  24470. const data = getLightData( light );
  24471. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24472. if ( light.castShadow !== true ) {
  24473. light.shadow.updateMatrices( light );
  24474. }
  24475. return light.shadow.matrix;
  24476. } ) );
  24477. }
  24478. /**
  24479. * TSL function for getting projected uv coordinates for the given light.
  24480. * Relevant when using maps with spot lights.
  24481. *
  24482. * @function
  24483. * @param {Light} light -The light source.
  24484. * @returns {Node<vec3>} The projected uvs.
  24485. */
  24486. function lightProjectionUV( light ) {
  24487. const data = getLightData( light );
  24488. if ( data.projectionUV === undefined ) {
  24489. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24490. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24491. }
  24492. return data.projectionUV;
  24493. }
  24494. /**
  24495. * TSL function for getting the position in world space for the given light.
  24496. *
  24497. * @function
  24498. * @param {Light} light -The light source.
  24499. * @returns {UniformNode<vec3>} The light's position in world space.
  24500. */
  24501. function lightPosition( light ) {
  24502. const data = getLightData( light );
  24503. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24504. }
  24505. /**
  24506. * TSL function for getting the light target position in world space for the given light.
  24507. *
  24508. * @function
  24509. * @param {Light} light -The light source.
  24510. * @returns {UniformNode<vec3>} The light target position in world space.
  24511. */
  24512. function lightTargetPosition( light ) {
  24513. const data = getLightData( light );
  24514. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24515. }
  24516. /**
  24517. * TSL function for getting the position in view space for the given light.
  24518. *
  24519. * @function
  24520. * @param {Light} light -The light source.
  24521. * @returns {UniformNode<vec3>} The light's position in view space.
  24522. */
  24523. function lightViewPosition( light ) {
  24524. const data = getLightData( light );
  24525. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24526. self.value = self.value || new Vector3();
  24527. self.value.setFromMatrixPosition( light.matrixWorld );
  24528. self.value.applyMatrix4( camera.matrixWorldInverse );
  24529. } ) );
  24530. }
  24531. /**
  24532. * TSL function for getting the light target direction for the given light.
  24533. *
  24534. * @function
  24535. * @param {Light} light -The light source.
  24536. * @returns {Node<vec3>} The light's target direction.
  24537. */
  24538. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24539. /** @module LightsNode **/
  24540. const sortLights = ( lights ) => {
  24541. return lights.sort( ( a, b ) => a.id - b.id );
  24542. };
  24543. const getLightNodeById = ( id, lightNodes ) => {
  24544. for ( const lightNode of lightNodes ) {
  24545. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24546. return lightNode;
  24547. }
  24548. }
  24549. return null;
  24550. };
  24551. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24552. /**
  24553. * This node represents the scene's lighting and manages the lighting model's life cycle
  24554. * for the current build 3D object. It is responsible for computing the total outgoing
  24555. * light in a given lighting context.
  24556. *
  24557. * @augments Node
  24558. */
  24559. class LightsNode extends Node {
  24560. static get type() {
  24561. return 'LightsNode';
  24562. }
  24563. /**
  24564. * Constructs a new lights node.
  24565. */
  24566. constructor() {
  24567. super( 'vec3' );
  24568. /**
  24569. * A node representing the total diffuse light.
  24570. *
  24571. * @type {Node<vec3>}
  24572. */
  24573. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24574. /**
  24575. * A node representing the total specular light.
  24576. *
  24577. * @type {Node<vec3>}
  24578. */
  24579. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24580. /**
  24581. * A node representing the outgoing light.
  24582. *
  24583. * @type {Node<vec3>}
  24584. */
  24585. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24586. /**
  24587. * An array representing the lights in the scene.
  24588. *
  24589. * @private
  24590. * @type {Array<Light>}
  24591. */
  24592. this._lights = [];
  24593. /**
  24594. * For each light in the scene, this node will create a
  24595. * corresponding light node.
  24596. *
  24597. * @private
  24598. * @type {Array<LightingNode>?}
  24599. * @default null
  24600. */
  24601. this._lightNodes = null;
  24602. /**
  24603. * A hash for identifying the current light nodes setup.
  24604. *
  24605. * @private
  24606. * @type {String?}
  24607. * @default null
  24608. */
  24609. this._lightNodesHash = null;
  24610. /**
  24611. * `LightsNode` sets this property to `true` by default.
  24612. *
  24613. * @type {Boolean}
  24614. * @default true
  24615. */
  24616. this.global = true;
  24617. }
  24618. /**
  24619. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24620. * light IDs into the cache key.
  24621. *
  24622. * @return {Number} The custom cache key.
  24623. */
  24624. customCacheKey() {
  24625. const lightIDs = [];
  24626. const lights = this._lights;
  24627. for ( let i = 0; i < lights.length; i ++ ) {
  24628. lightIDs.push( lights[ i ].id );
  24629. }
  24630. return hashArray( lightIDs );
  24631. }
  24632. /**
  24633. * Computes a hash value for identifying the current light nodes setup.
  24634. *
  24635. * @param {NodeBuilder} builder - A reference to the current node builder.
  24636. * @return {String} The computed hash.
  24637. */
  24638. getHash( builder ) {
  24639. if ( this._lightNodesHash === null ) {
  24640. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24641. const hash = [];
  24642. for ( const lightNode of this._lightNodes ) {
  24643. hash.push( lightNode.getSelf().getHash() );
  24644. }
  24645. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24646. }
  24647. return this._lightNodesHash;
  24648. }
  24649. analyze( builder ) {
  24650. const properties = builder.getDataFromNode( this );
  24651. for ( const node of properties.nodes ) {
  24652. node.build( builder );
  24653. }
  24654. }
  24655. /**
  24656. * Creates lighting nodes for each scene light. This makes it possible to further
  24657. * process lights in the node system.
  24658. *
  24659. * @param {NodeBuilder} builder - A reference to the current node builder.
  24660. */
  24661. setupLightsNode( builder ) {
  24662. const lightNodes = [];
  24663. const previousLightNodes = this._lightNodes;
  24664. const lights = sortLights( this._lights );
  24665. const nodeLibrary = builder.renderer.library;
  24666. for ( const light of lights ) {
  24667. if ( light.isNode ) {
  24668. lightNodes.push( nodeObject( light ) );
  24669. } else {
  24670. let lightNode = null;
  24671. if ( previousLightNodes !== null ) {
  24672. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24673. }
  24674. if ( lightNode === null ) {
  24675. // find the corresponding node type for a given light
  24676. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24677. if ( lightNodeClass === null ) {
  24678. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24679. continue;
  24680. }
  24681. let lightNode = null;
  24682. if ( ! _lightsNodeRef.has( light ) ) {
  24683. lightNode = nodeObject( new lightNodeClass( light ) );
  24684. _lightsNodeRef.set( light, lightNode );
  24685. } else {
  24686. lightNode = _lightsNodeRef.get( light );
  24687. }
  24688. lightNodes.push( lightNode );
  24689. }
  24690. }
  24691. }
  24692. this._lightNodes = lightNodes;
  24693. }
  24694. /**
  24695. * Setups the internal lights by building all respective
  24696. * light nodes.
  24697. *
  24698. * @param {NodeBuilder} builder - A reference to the current node builder.
  24699. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24700. */
  24701. setupLights( builder, lightNodes ) {
  24702. for ( const lightNode of lightNodes ) {
  24703. lightNode.build( builder );
  24704. }
  24705. }
  24706. /**
  24707. * The implementation makes sure that for each light in the scene
  24708. * there is a corresponding light node. By building the light nodes
  24709. * and evaluating the lighting model the outgoing light is computed.
  24710. *
  24711. * @param {NodeBuilder} builder - A reference to the current node builder.
  24712. * @return {Node<vec3>} A node representing the outgoing light.
  24713. */
  24714. setup( builder ) {
  24715. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24716. const context = builder.context;
  24717. const lightingModel = context.lightingModel;
  24718. let outgoingLightNode = this.outgoingLightNode;
  24719. if ( lightingModel ) {
  24720. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24721. context.outgoingLight = outgoingLightNode;
  24722. const stack = builder.addStack();
  24723. //
  24724. const properties = builder.getDataFromNode( this );
  24725. properties.nodes = stack.nodes;
  24726. //
  24727. lightingModel.start( context, stack, builder );
  24728. // lights
  24729. this.setupLights( builder, _lightNodes );
  24730. //
  24731. lightingModel.indirect( context, stack, builder );
  24732. //
  24733. const { backdrop, backdropAlpha } = context;
  24734. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24735. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24736. if ( backdrop !== null ) {
  24737. if ( backdropAlpha !== null ) {
  24738. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24739. } else {
  24740. totalDiffuse = vec3( backdrop );
  24741. }
  24742. context.material.transparent = true;
  24743. }
  24744. totalDiffuseNode.assign( totalDiffuse );
  24745. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24746. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24747. //
  24748. lightingModel.finish( context, stack, builder );
  24749. //
  24750. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24751. }
  24752. return outgoingLightNode;
  24753. }
  24754. /**
  24755. * Configures this node with an array of lights.
  24756. *
  24757. * @param {Array<Light>} lights - An array of lights.
  24758. * @return {LightsNode} A reference to this node.
  24759. */
  24760. setLights( lights ) {
  24761. this._lights = lights;
  24762. this._lightNodes = null;
  24763. this._lightNodesHash = null;
  24764. return this;
  24765. }
  24766. /**
  24767. * Returns an array of the scene's lights.
  24768. *
  24769. * @return {Array<Light>} The scene's lights.
  24770. */
  24771. getLights() {
  24772. return this._lights;
  24773. }
  24774. /**
  24775. * Whether the scene has lights or not.
  24776. *
  24777. * @type {Boolean}
  24778. */
  24779. get hasLights() {
  24780. return this._lights.length > 0;
  24781. }
  24782. }
  24783. /**
  24784. * TSL function for creating an instance of `LightsNode` and configuring
  24785. * it with the given array of lights.
  24786. *
  24787. * @function
  24788. * @param {Array<Light>} lights - An array of lights.
  24789. * @return {LightsNode} The created lights node.
  24790. */
  24791. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24792. /** @module ShadowBaseNode **/
  24793. /**
  24794. * Base class for all shadow nodes.
  24795. *
  24796. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24797. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24798. * their requirements.
  24799. *
  24800. * @augments Node
  24801. */
  24802. class ShadowBaseNode extends Node {
  24803. static get type() {
  24804. return 'ShadowBaseNode';
  24805. }
  24806. /**
  24807. * Constructs a new shadow base node.
  24808. *
  24809. * @param {Light} light - The shadow casting light.
  24810. */
  24811. constructor( light ) {
  24812. super();
  24813. /**
  24814. * The shadow casting light.
  24815. *
  24816. * @type {Light}
  24817. */
  24818. this.light = light;
  24819. /**
  24820. * Overwritten since shadows are updated by default per render.
  24821. *
  24822. * @type {String}
  24823. * @default 'render'
  24824. */
  24825. this.updateBeforeType = NodeUpdateType.RENDER;
  24826. /**
  24827. * This flag can be used for type testing.
  24828. *
  24829. * @type {Boolean}
  24830. * @readonly
  24831. * @default true
  24832. */
  24833. this.isShadowBaseNode = true;
  24834. }
  24835. /**
  24836. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24837. *
  24838. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24839. */
  24840. setupShadowPosition( { material } ) {
  24841. // Use assign inside an Fn()
  24842. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24843. }
  24844. /**
  24845. * Can be called when the shadow isn't required anymore. That can happen when
  24846. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24847. * to `false`.
  24848. */
  24849. dispose() {
  24850. this.updateBeforeType = NodeUpdateType.NONE;
  24851. }
  24852. }
  24853. /**
  24854. * TSL object that represents the vertex position in world space during the shadow pass.
  24855. *
  24856. * @type {Node<vec3>}
  24857. */
  24858. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24859. /** @module RendererUtils **/
  24860. /**
  24861. * Saves the state of the given renderer and stores it into the given state object.
  24862. *
  24863. * If not state object is provided, the function creates one.
  24864. *
  24865. * @function
  24866. * @param {Renderer} renderer - The renderer.
  24867. * @param {Object} [state={}] - The state.
  24868. * @return {Object} The state.
  24869. */
  24870. function saveRendererState( renderer, state = {} ) {
  24871. state.toneMapping = renderer.toneMapping;
  24872. state.toneMappingExposure = renderer.toneMappingExposure;
  24873. state.outputColorSpace = renderer.outputColorSpace;
  24874. state.renderTarget = renderer.getRenderTarget();
  24875. state.activeCubeFace = renderer.getActiveCubeFace();
  24876. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24877. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24878. state.pixelRatio = renderer.getPixelRatio();
  24879. state.mrt = renderer.getMRT();
  24880. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24881. state.clearAlpha = renderer.getClearAlpha();
  24882. state.autoClear = renderer.autoClear;
  24883. state.scissorTest = renderer.getScissorTest();
  24884. return state;
  24885. }
  24886. /**
  24887. * Saves the state of the given renderer and stores it into the given state object.
  24888. * Besides, the function also resets the state of the renderer to its default values.
  24889. *
  24890. * If not state object is provided, the function creates one.
  24891. *
  24892. * @function
  24893. * @param {Renderer} renderer - The renderer.
  24894. * @param {Object} [state={}] - The state.
  24895. * @return {Object} The state.
  24896. */
  24897. function resetRendererState( renderer, state ) {
  24898. state = saveRendererState( renderer, state );
  24899. renderer.setMRT( null );
  24900. renderer.setRenderObjectFunction( null );
  24901. renderer.setClearColor( 0x000000, 1 );
  24902. renderer.autoClear = true;
  24903. return state;
  24904. }
  24905. /**
  24906. * Restores the state of the given renderer from the given state object.
  24907. *
  24908. * @function
  24909. * @param {Renderer} renderer - The renderer.
  24910. * @param {Object} state - The state to restore.
  24911. */
  24912. function restoreRendererState( renderer, state ) {
  24913. renderer.toneMapping = state.toneMapping;
  24914. renderer.toneMappingExposure = state.toneMappingExposure;
  24915. renderer.outputColorSpace = state.outputColorSpace;
  24916. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24917. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24918. renderer.setPixelRatio( state.pixelRatio );
  24919. renderer.setMRT( state.mrt );
  24920. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24921. renderer.autoClear = state.autoClear;
  24922. renderer.setScissorTest( state.scissorTest );
  24923. }
  24924. /**
  24925. * Saves the state of the given scene and stores it into the given state object.
  24926. *
  24927. * If not state object is provided, the function creates one.
  24928. *
  24929. * @function
  24930. * @param {Scene} scene - The scene.
  24931. * @param {Object} [state={}] - The state.
  24932. * @return {Object} The state.
  24933. */
  24934. function saveSceneState( scene, state = {} ) {
  24935. state.background = scene.background;
  24936. state.backgroundNode = scene.backgroundNode;
  24937. state.overrideMaterial = scene.overrideMaterial;
  24938. return state;
  24939. }
  24940. /**
  24941. * Saves the state of the given scene and stores it into the given state object.
  24942. * Besides, the function also resets the state of the scene to its default values.
  24943. *
  24944. * If not state object is provided, the function creates one.
  24945. *
  24946. * @function
  24947. * @param {Scene} scene - The scene.
  24948. * @param {Object} [state={}] - The state.
  24949. * @return {Object} The state.
  24950. */
  24951. function resetSceneState( scene, state ) {
  24952. state = saveSceneState( scene, state );
  24953. scene.background = null;
  24954. scene.backgroundNode = null;
  24955. scene.overrideMaterial = null;
  24956. return state;
  24957. }
  24958. /**
  24959. * Restores the state of the given scene from the given state object.
  24960. *
  24961. * @function
  24962. * @param {Scene} scene - The scene.
  24963. * @param {Object} state - The state to restore.
  24964. */
  24965. function restoreSceneState( scene, state ) {
  24966. scene.background = state.background;
  24967. scene.backgroundNode = state.backgroundNode;
  24968. scene.overrideMaterial = state.overrideMaterial;
  24969. }
  24970. /**
  24971. * Saves the state of the given renderer and scene and stores it into the given state object.
  24972. *
  24973. * If not state object is provided, the function creates one.
  24974. *
  24975. * @function
  24976. * @param {Renderer} renderer - The renderer.
  24977. * @param {Scene} scene - The scene.
  24978. * @param {Object} [state={}] - The state.
  24979. * @return {Object} The state.
  24980. */
  24981. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24982. state = saveRendererState( renderer, state );
  24983. state = saveSceneState( scene, state );
  24984. return state;
  24985. }
  24986. /**
  24987. * Saves the state of the given renderer and scene and stores it into the given state object.
  24988. * Besides, the function also resets the state of the renderer and scene to its default values.
  24989. *
  24990. * If not state object is provided, the function creates one.
  24991. *
  24992. * @function
  24993. * @param {Renderer} renderer - The renderer.
  24994. * @param {Scene} scene - The scene.
  24995. * @param {Object} [state={}] - The state.
  24996. * @return {Object} The state.
  24997. */
  24998. function resetRendererAndSceneState( renderer, scene, state ) {
  24999. state = resetRendererState( renderer, state );
  25000. state = resetSceneState( scene, state );
  25001. return state;
  25002. }
  25003. /**
  25004. * Restores the state of the given renderer and scene from the given state object.
  25005. *
  25006. * @function
  25007. * @param {Renderer} renderer - The renderer.
  25008. * @param {Scene} scene - The scene.
  25009. * @param {Object} state - The state to restore.
  25010. */
  25011. function restoreRendererAndSceneState( renderer, scene, state ) {
  25012. restoreRendererState( renderer, state );
  25013. restoreSceneState( scene, state );
  25014. }
  25015. var RendererUtils = /*#__PURE__*/Object.freeze({
  25016. __proto__: null,
  25017. resetRendererAndSceneState: resetRendererAndSceneState,
  25018. resetRendererState: resetRendererState,
  25019. resetSceneState: resetSceneState,
  25020. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25021. restoreRendererState: restoreRendererState,
  25022. restoreSceneState: restoreSceneState,
  25023. saveRendererAndSceneState: saveRendererAndSceneState,
  25024. saveRendererState: saveRendererState,
  25025. saveSceneState: saveSceneState
  25026. });
  25027. /** @module ShadowNode **/
  25028. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25029. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25030. let dist = positionWorld.sub( position ).length();
  25031. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25032. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25033. return dist;
  25034. } );
  25035. const linearShadowDistance = ( light ) => {
  25036. const camera = light.shadow.camera;
  25037. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25038. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25039. const referencePosition = objectPosition( light );
  25040. return linearDistance( referencePosition, nearDistance, farDistance );
  25041. };
  25042. const getShadowMaterial = ( light ) => {
  25043. let material = shadowMaterialLib.get( light );
  25044. if ( material === undefined ) {
  25045. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25046. material = new NodeMaterial();
  25047. material.colorNode = vec4( 0, 0, 0, 1 );
  25048. material.depthNode = depthNode;
  25049. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25050. material.name = 'ShadowMaterial';
  25051. material.fog = false;
  25052. shadowMaterialLib.set( light, material );
  25053. }
  25054. return material;
  25055. };
  25056. /**
  25057. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25058. * with a binary `[0,1]` result.
  25059. *
  25060. * @method
  25061. * @param {Object} inputs - The input parameter object.
  25062. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25063. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25064. * @return {Node<float>} The filtering result.
  25065. */
  25066. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25067. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25068. } );
  25069. /**
  25070. * A shadow filtering function performing PCF filtering.
  25071. *
  25072. * @method
  25073. * @param {Object} inputs - The input parameter object.
  25074. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25075. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25076. * @param {LightShadow} inputs.shadow - The light shadow.
  25077. * @return {Node<float>} The filtering result.
  25078. */
  25079. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25080. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25081. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25082. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25083. const texelSize = vec2( 1 ).div( mapSize );
  25084. const dx0 = texelSize.x.negate().mul( radius );
  25085. const dy0 = texelSize.y.negate().mul( radius );
  25086. const dx1 = texelSize.x.mul( radius );
  25087. const dy1 = texelSize.y.mul( radius );
  25088. const dx2 = dx0.div( 2 );
  25089. const dy2 = dy0.div( 2 );
  25090. const dx3 = dx1.div( 2 );
  25091. const dy3 = dy1.div( 2 );
  25092. return add(
  25093. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25094. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25095. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25096. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25097. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25098. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25099. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25100. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25101. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25102. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25103. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25104. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25105. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25106. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25107. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25108. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25109. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25110. ).mul( 1 / 17 );
  25111. } );
  25112. /**
  25113. * A shadow filtering function performing PCF soft filtering.
  25114. *
  25115. * @method
  25116. * @param {Object} inputs - The input parameter object.
  25117. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25118. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25119. * @param {LightShadow} inputs.shadow - The light shadow.
  25120. * @return {Node<float>} The filtering result.
  25121. */
  25122. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25123. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25124. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25125. const texelSize = vec2( 1 ).div( mapSize );
  25126. const dx = texelSize.x;
  25127. const dy = texelSize.y;
  25128. const uv = shadowCoord.xy;
  25129. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25130. uv.subAssign( f.mul( texelSize ) );
  25131. return add(
  25132. depthCompare( uv, shadowCoord.z ),
  25133. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25134. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25135. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25136. mix(
  25137. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25138. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25139. f.x
  25140. ),
  25141. mix(
  25142. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25143. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25144. f.x
  25145. ),
  25146. mix(
  25147. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25148. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25149. f.y
  25150. ),
  25151. mix(
  25152. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25153. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25154. f.y
  25155. ),
  25156. mix(
  25157. mix(
  25158. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25159. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25160. f.x
  25161. ),
  25162. mix(
  25163. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25164. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25165. f.x
  25166. ),
  25167. f.y
  25168. )
  25169. ).mul( 1 / 9 );
  25170. } );
  25171. /**
  25172. * A shadow filtering function performing VSM filtering.
  25173. *
  25174. * @method
  25175. * @param {Object} inputs - The input parameter object.
  25176. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25177. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25178. * @return {Node<float>} The filtering result.
  25179. */
  25180. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25181. const occlusion = float( 1 ).toVar();
  25182. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25183. const hardShadow = step( shadowCoord.z, distribution.x );
  25184. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25185. const distance = shadowCoord.z.sub( distribution.x );
  25186. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25187. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25188. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25189. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25190. } );
  25191. return occlusion;
  25192. } );
  25193. /**
  25194. * Represents the shader code for the first VSM render pass.
  25195. *
  25196. * @method
  25197. * @param {Object} inputs - The input parameter object.
  25198. * @param {Node<float>} inputs.samples - The number of samples
  25199. * @param {Node<float>} inputs.radius - The radius.
  25200. * @param {Node<float>} inputs.size - The size.
  25201. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25202. * @return {Node<vec2>} The VSM output.
  25203. */
  25204. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25205. const mean = float( 0 ).toVar();
  25206. const squaredMean = float( 0 ).toVar();
  25207. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25208. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25209. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25210. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25211. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25212. mean.addAssign( depth );
  25213. squaredMean.addAssign( depth.mul( depth ) );
  25214. } );
  25215. mean.divAssign( samples );
  25216. squaredMean.divAssign( samples );
  25217. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25218. return vec2( mean, std_dev );
  25219. } );
  25220. /**
  25221. * Represents the shader code for the second VSM render pass.
  25222. *
  25223. * @method
  25224. * @param {Object} inputs - The input parameter object.
  25225. * @param {Node<float>} inputs.samples - The number of samples
  25226. * @param {Node<float>} inputs.radius - The radius.
  25227. * @param {Node<float>} inputs.size - The size.
  25228. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25229. * @return {Node<vec2>} The VSM output.
  25230. */
  25231. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25232. const mean = float( 0 ).toVar();
  25233. const squaredMean = float( 0 ).toVar();
  25234. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25235. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25236. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25237. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25238. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25239. mean.addAssign( distribution.x );
  25240. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25241. } );
  25242. mean.divAssign( samples );
  25243. squaredMean.divAssign( samples );
  25244. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25245. return vec2( mean, std_dev );
  25246. } );
  25247. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25248. //
  25249. let _rendererState;
  25250. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25251. /**
  25252. * Represents the default shadow implementation for lighting nodes.
  25253. *
  25254. * @augments module:ShadowBaseNode~ShadowBaseNode
  25255. */
  25256. class ShadowNode extends ShadowBaseNode {
  25257. static get type() {
  25258. return 'ShadowNode';
  25259. }
  25260. /**
  25261. * Constructs a new shadow node.
  25262. *
  25263. * @param {Light} light - The shadow casting light.
  25264. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25265. */
  25266. constructor( light, shadow = null ) {
  25267. super( light );
  25268. /**
  25269. * The light shadow which defines the properties light's
  25270. * shadow.
  25271. *
  25272. * @type {LightShadow?}
  25273. * @default null
  25274. */
  25275. this.shadow = shadow || light.shadow;
  25276. /**
  25277. * A reference to the shadow map which is a render target.
  25278. *
  25279. * @type {RenderTarget?}
  25280. * @default null
  25281. */
  25282. this.shadowMap = null;
  25283. /**
  25284. * Only relevant for VSM shadows. Render target for the
  25285. * first VSM render pass.
  25286. *
  25287. * @type {RenderTarget?}
  25288. * @default null
  25289. */
  25290. this.vsmShadowMapVertical = null;
  25291. /**
  25292. * Only relevant for VSM shadows. Render target for the
  25293. * second VSM render pass.
  25294. *
  25295. * @type {RenderTarget?}
  25296. * @default null
  25297. */
  25298. this.vsmShadowMapHorizontal = null;
  25299. /**
  25300. * Only relevant for VSM shadows. Node material which
  25301. * is used to render the first VSM pass.
  25302. *
  25303. * @type {NodeMaterial?}
  25304. * @default null
  25305. */
  25306. this.vsmMaterialVertical = null;
  25307. /**
  25308. * Only relevant for VSM shadows. Node material which
  25309. * is used to render the second VSM pass.
  25310. *
  25311. * @type {NodeMaterial?}
  25312. * @default null
  25313. */
  25314. this.vsmMaterialHorizontal = null;
  25315. /**
  25316. * A reference to the output node which defines the
  25317. * final result of this shadow node.
  25318. *
  25319. * @type {Node?}
  25320. * @private
  25321. * @default null
  25322. */
  25323. this._node = null;
  25324. /**
  25325. * This flag can be used for type testing.
  25326. *
  25327. * @type {Boolean}
  25328. * @readonly
  25329. * @default true
  25330. */
  25331. this.isShadowNode = true;
  25332. }
  25333. /**
  25334. * Setups the shadow filtering.
  25335. *
  25336. * @param {NodeBuilder} builder - A reference to the current node builder.
  25337. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25338. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25339. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25340. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25341. * @param {LightShadow} inputs.shadow - The light shadow.
  25342. * @return {Node<float>} The result node of the shadow filtering.
  25343. */
  25344. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25345. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25346. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25347. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25348. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25349. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25350. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25351. return frustumTest.select( shadowNode, float( 1 ) );
  25352. }
  25353. /**
  25354. * Setups the shadow coordinates.
  25355. *
  25356. * @param {NodeBuilder} builder - A reference to the current node builder.
  25357. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25358. * @return {Node<vec3>} The shadow coordinates.
  25359. */
  25360. setupShadowCoord( builder, shadowPosition ) {
  25361. const { shadow } = this;
  25362. const { renderer } = builder;
  25363. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25364. let shadowCoord = shadowPosition;
  25365. let coordZ;
  25366. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25367. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25368. coordZ = shadowCoord.z;
  25369. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25370. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25371. }
  25372. } else {
  25373. const w = shadowCoord.w;
  25374. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25375. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25376. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25377. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25378. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25379. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25380. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25381. }
  25382. shadowCoord = vec3(
  25383. shadowCoord.x,
  25384. shadowCoord.y.oneMinus(), // follow webgpu standards
  25385. coordZ.add( bias )
  25386. );
  25387. return shadowCoord;
  25388. }
  25389. /**
  25390. * Returns the shadow filtering function for the given shadow type.
  25391. *
  25392. * @param {Number} type - The shadow type.
  25393. * @return {Function} The filtering function.
  25394. */
  25395. getShadowFilterFn( type ) {
  25396. return _shadowFilterLib[ type ];
  25397. }
  25398. /**
  25399. * Setups the shadow output node.
  25400. *
  25401. * @param {NodeBuilder} builder - A reference to the current node builder.
  25402. * @return {Node<vec3>} The shadow output node.
  25403. */
  25404. setupShadow( builder ) {
  25405. const { renderer } = builder;
  25406. const { light, shadow } = this;
  25407. const shadowMapType = renderer.shadowMap.type;
  25408. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25409. depthTexture.compareFunction = LessCompare;
  25410. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25411. shadowMap.depthTexture = depthTexture;
  25412. shadow.camera.updateProjectionMatrix();
  25413. // VSM
  25414. if ( shadowMapType === VSMShadowMap ) {
  25415. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25416. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25417. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25418. const shadowPassVertical = texture( depthTexture );
  25419. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25420. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25421. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25422. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25423. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25424. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25425. material.name = 'VSMVertical';
  25426. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25427. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25428. material.name = 'VSMHorizontal';
  25429. }
  25430. //
  25431. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25432. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25433. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25434. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25435. //
  25436. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25437. if ( filterFn === null ) {
  25438. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25439. }
  25440. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25441. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25442. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25443. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25444. this.shadowMap = shadowMap;
  25445. this.shadow.map = shadowMap;
  25446. return shadowOutput;
  25447. }
  25448. /**
  25449. * The implementation performs the setup of the output node. An output is only
  25450. * produces if shadow mapping is globally enabled in the renderer.
  25451. *
  25452. * @param {NodeBuilder} builder - A reference to the current node builder.
  25453. * @return {ShaderCallNodeInternal} The output node.
  25454. */
  25455. setup( builder ) {
  25456. if ( builder.renderer.shadowMap.enabled === false ) return;
  25457. return Fn( () => {
  25458. let node = this._node;
  25459. this.setupShadowPosition( builder );
  25460. if ( node === null ) {
  25461. this._node = node = this.setupShadow( builder );
  25462. }
  25463. if ( builder.material.shadowNode ) { // @deprecated, r171
  25464. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25465. }
  25466. if ( builder.material.receivedShadowNode ) {
  25467. node = builder.material.receivedShadowNode( node );
  25468. }
  25469. return node;
  25470. } )();
  25471. }
  25472. /**
  25473. * Renders the shadow. The logic of this function could be included
  25474. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25475. * nodes might require a custom shadow map rendering. By having a
  25476. * dedicated method, it's easier to overwrite the default behavior.
  25477. *
  25478. * @param {NodeFrame} frame - A reference to the current node frame.
  25479. */
  25480. renderShadow( frame ) {
  25481. const { shadow, shadowMap, light } = this;
  25482. const { renderer, scene } = frame;
  25483. shadow.updateMatrices( light );
  25484. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25485. renderer.render( scene, shadow.camera );
  25486. }
  25487. /**
  25488. * Updates the shadow.
  25489. *
  25490. * @param {NodeFrame} frame - A reference to the current node frame.
  25491. */
  25492. updateShadow( frame ) {
  25493. const { shadowMap, light, shadow } = this;
  25494. const { renderer, scene, camera } = frame;
  25495. const shadowType = renderer.shadowMap.type;
  25496. const depthVersion = shadowMap.depthTexture.version;
  25497. this._depthVersionCached = depthVersion;
  25498. shadow.camera.layers.mask = camera.layers.mask;
  25499. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25500. const currentMRT = renderer.getMRT();
  25501. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25502. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25503. scene.overrideMaterial = getShadowMaterial( light );
  25504. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25505. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25506. if ( useVelocity ) {
  25507. getDataFromObject( object ).useVelocity = true;
  25508. }
  25509. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25510. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25511. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25512. }
  25513. } );
  25514. renderer.setRenderTarget( shadowMap );
  25515. this.renderShadow( frame );
  25516. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25517. // vsm blur pass
  25518. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25519. this.vsmPass( renderer );
  25520. }
  25521. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25522. }
  25523. /**
  25524. * For VSM additional render passes are required.
  25525. *
  25526. * @param {Renderer} renderer - A reference to the current renderer.
  25527. */
  25528. vsmPass( renderer ) {
  25529. const { shadow } = this;
  25530. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25531. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25532. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25533. _quadMesh.material = this.vsmMaterialVertical;
  25534. _quadMesh.render( renderer );
  25535. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25536. _quadMesh.material = this.vsmMaterialHorizontal;
  25537. _quadMesh.render( renderer );
  25538. }
  25539. /**
  25540. * Frees the internal resources of this shadow node.
  25541. */
  25542. dispose() {
  25543. this.shadowMap.dispose();
  25544. this.shadowMap = null;
  25545. if ( this.vsmShadowMapVertical !== null ) {
  25546. this.vsmShadowMapVertical.dispose();
  25547. this.vsmShadowMapVertical = null;
  25548. this.vsmMaterialVertical.dispose();
  25549. this.vsmMaterialVertical = null;
  25550. }
  25551. if ( this.vsmShadowMapHorizontal !== null ) {
  25552. this.vsmShadowMapHorizontal.dispose();
  25553. this.vsmShadowMapHorizontal = null;
  25554. this.vsmMaterialHorizontal.dispose();
  25555. this.vsmMaterialHorizontal = null;
  25556. }
  25557. super.dispose();
  25558. }
  25559. /**
  25560. * The implementation performs the update of the shadow map if necessary.
  25561. *
  25562. * @param {NodeFrame} frame - A reference to the current node frame.
  25563. */
  25564. updateBefore( frame ) {
  25565. const { shadow } = this;
  25566. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25567. if ( needsUpdate ) {
  25568. this.updateShadow( frame );
  25569. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25570. shadow.needsUpdate = false;
  25571. }
  25572. }
  25573. }
  25574. }
  25575. /**
  25576. * TSL function for creating an instance of `ShadowNode`.
  25577. *
  25578. * @function
  25579. * @param {Light} light - The shadow casting light.
  25580. * @param {LightShadow} shadow - The light shadow.
  25581. * @return {ShadowNode} The created shadow node.
  25582. */
  25583. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25584. /**
  25585. * Base class for analytic light nodes.
  25586. *
  25587. * @augments LightingNode
  25588. */
  25589. class AnalyticLightNode extends LightingNode {
  25590. static get type() {
  25591. return 'AnalyticLightNode';
  25592. }
  25593. /**
  25594. * Constructs a new analytic light node.
  25595. *
  25596. * @param {Light?} [light=null] - The light source.
  25597. */
  25598. constructor( light = null ) {
  25599. super();
  25600. /**
  25601. * The light source.
  25602. *
  25603. * @type {Light?}
  25604. * @default null
  25605. */
  25606. this.light = light;
  25607. /**
  25608. * The light's color value.
  25609. *
  25610. * @type {Color}
  25611. */
  25612. this.color = new Color();
  25613. /**
  25614. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25615. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25616. *
  25617. * @type {Node}
  25618. */
  25619. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25620. /**
  25621. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25622. * The final color node is represented by a different node when using shadows.
  25623. *
  25624. * @type {Node?}
  25625. * @default null
  25626. */
  25627. this.baseColorNode = null;
  25628. /**
  25629. * Represents the light's shadow.
  25630. *
  25631. * @type {ShadowNode?}
  25632. * @default null
  25633. */
  25634. this.shadowNode = null;
  25635. /**
  25636. * Represents the light's shadow color.
  25637. *
  25638. * @type {Node?}
  25639. * @default null
  25640. */
  25641. this.shadowColorNode = null;
  25642. /**
  25643. * This flag can be used for type testing.
  25644. *
  25645. * @type {Boolean}
  25646. * @readonly
  25647. * @default true
  25648. */
  25649. this.isAnalyticLightNode = true;
  25650. /**
  25651. * Overwritten since analytic light nodes are updated
  25652. * once per frame.
  25653. *
  25654. * @type {String}
  25655. * @default 'frame'
  25656. */
  25657. this.updateType = NodeUpdateType.FRAME;
  25658. }
  25659. /**
  25660. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25661. * `light.id` and `light.castShadow` into the cache key.
  25662. *
  25663. * @return {Number} The custom cache key.
  25664. */
  25665. customCacheKey() {
  25666. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25667. }
  25668. getHash() {
  25669. return this.light.uuid;
  25670. }
  25671. /**
  25672. * Setups the shadow node for this light. The method exists so concrete light classes
  25673. * can setup different types of shadow nodes.
  25674. *
  25675. * @return {ShadowNode} The created shadow node.
  25676. */
  25677. setupShadowNode() {
  25678. return shadow( this.light );
  25679. }
  25680. /**
  25681. * Setups the shadow for this light. This method is only executed if the light
  25682. * cast shadows and the current build object receives shadows. It incorporates
  25683. * shadows into the lighting computation.
  25684. *
  25685. * @param {NodeBuilder} builder - The current node builder.
  25686. */
  25687. setupShadow( builder ) {
  25688. const { renderer } = builder;
  25689. if ( renderer.shadowMap.enabled === false ) return;
  25690. let shadowColorNode = this.shadowColorNode;
  25691. if ( shadowColorNode === null ) {
  25692. const customShadowNode = this.light.shadow.shadowNode;
  25693. let shadowNode;
  25694. if ( customShadowNode !== undefined ) {
  25695. shadowNode = nodeObject( customShadowNode );
  25696. } else {
  25697. shadowNode = this.setupShadowNode( builder );
  25698. }
  25699. this.shadowNode = shadowNode;
  25700. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25701. this.baseColorNode = this.colorNode;
  25702. }
  25703. //
  25704. this.colorNode = shadowColorNode;
  25705. }
  25706. /**
  25707. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25708. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25709. * invocate the respective interface methods.
  25710. *
  25711. * @param {NodeBuilder} builder - The current node builder.
  25712. */
  25713. setup( builder ) {
  25714. this.colorNode = this.baseColorNode || this.colorNode;
  25715. if ( this.light.castShadow ) {
  25716. if ( builder.object.receiveShadow ) {
  25717. this.setupShadow( builder );
  25718. }
  25719. } else if ( this.shadowNode !== null ) {
  25720. this.shadowNode.dispose();
  25721. this.shadowNode = null;
  25722. this.shadowColorNode = null;
  25723. }
  25724. }
  25725. /**
  25726. * The update method is used to update light uniforms per frame.
  25727. * Potentially overwritten in concrete light nodes to update light
  25728. * specific uniforms.
  25729. *
  25730. * @param {NodeFrame} frame - A reference to the current node frame.
  25731. */
  25732. update( /*frame*/ ) {
  25733. const { light } = this;
  25734. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25735. }
  25736. }
  25737. /** @module LightUtils **/
  25738. /**
  25739. * Represents a `discard` shader operation in TSL.
  25740. *
  25741. * @method
  25742. * @param {Object} inputs - The input parameter object.
  25743. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25744. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25745. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25746. * @return {Node<float>} The distance falloff.
  25747. */
  25748. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25749. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25750. // based upon Frostbite 3 Moving to Physically-based Rendering
  25751. // page 32, equation 26: E[window1]
  25752. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25753. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25754. return cutoffDistance.greaterThan( 0 ).select(
  25755. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25756. distanceFalloff
  25757. );
  25758. } ); // validated
  25759. /** @module PointShadowNode **/
  25760. const _clearColor$2 = /*@__PURE__*/ new Color();
  25761. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25762. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25763. // 2D texture:
  25764. //
  25765. // xzXZ
  25766. // y Y
  25767. //
  25768. // Y - Positive y direction
  25769. // y - Negative y direction
  25770. // X - Positive x direction
  25771. // x - Negative x direction
  25772. // Z - Positive z direction
  25773. // z - Negative z direction
  25774. //
  25775. // Source and test bed:
  25776. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25777. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25778. const v = pos.toVar();
  25779. // Number of texels to avoid at the edge of each square
  25780. const absV = abs( v );
  25781. // Intersect unit cube
  25782. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25783. absV.mulAssign( scaleToCube );
  25784. // Apply scale to avoid seams
  25785. // two texels less per square (one texel will do for NEAREST)
  25786. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25787. // Unwrap
  25788. // space: -1 ... 1 range for each square
  25789. //
  25790. // #X## dim := ( 4 , 2 )
  25791. // # # center := ( 1 , 1 )
  25792. const planar = vec2( v.xy ).toVar();
  25793. const almostATexel = texelSizeY.mul( 1.5 );
  25794. const almostOne = almostATexel.oneMinus();
  25795. If( absV.z.greaterThanEqual( almostOne ), () => {
  25796. If( v.z.greaterThan( 0.0 ), () => {
  25797. planar.x.assign( sub( 4.0, v.x ) );
  25798. } );
  25799. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25800. const signX = sign( v.x );
  25801. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25802. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25803. const signY = sign( v.y );
  25804. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25805. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25806. } );
  25807. // Transform to UV space
  25808. // scale := 0.5 / dim
  25809. // translate := ( center + 0.5 ) / dim
  25810. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25811. } ).setLayout( {
  25812. name: 'cubeToUV',
  25813. type: 'vec2',
  25814. inputs: [
  25815. { name: 'pos', type: 'vec3' },
  25816. { name: 'texelSizeY', type: 'float' }
  25817. ]
  25818. } );
  25819. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25820. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25821. } );
  25822. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25823. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25824. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25825. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25826. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25827. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25828. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25829. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25830. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25831. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25832. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25833. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25834. .mul( 1.0 / 9.0 );
  25835. } );
  25836. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25837. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25838. // the vector from the light to the world-space position of the fragment.
  25839. const lightToPosition = shadowCoord.xyz.toVar();
  25840. const lightToPositionLength = lightToPosition.length();
  25841. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25842. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25843. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25844. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25845. const result = float( 1.0 ).toVar();
  25846. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25847. // dp = normalized distance from light to fragment position
  25848. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25849. dp.addAssign( bias );
  25850. // bd3D = base direction 3D
  25851. const bd3D = lightToPosition.normalize();
  25852. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25853. // percentage-closer filtering
  25854. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25855. } );
  25856. return result;
  25857. } );
  25858. const _viewport = /*@__PURE__*/ new Vector4();
  25859. const _viewportSize = /*@__PURE__*/ new Vector2();
  25860. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25861. /**
  25862. * Represents the shadow implementation for point light nodes.
  25863. *
  25864. * @augments module:ShadowNode~ShadowNode
  25865. */
  25866. class PointShadowNode extends ShadowNode {
  25867. static get type() {
  25868. return 'PointShadowNode';
  25869. }
  25870. /**
  25871. * Constructs a new point shadow node.
  25872. *
  25873. * @param {PointLight} light - The shadow casting point light.
  25874. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25875. */
  25876. constructor( light, shadow = null ) {
  25877. super( light, shadow );
  25878. }
  25879. /**
  25880. * Overwrites the default implementation to return point light shadow specific
  25881. * filtering functions.
  25882. *
  25883. * @param {Number} type - The shadow type.
  25884. * @return {Function} The filtering function.
  25885. */
  25886. getShadowFilterFn( type ) {
  25887. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25888. }
  25889. /**
  25890. * Overwrites the default implementation so the unaltered shadow position is used.
  25891. *
  25892. * @param {NodeBuilder} builder - A reference to the current node builder.
  25893. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25894. * @return {Node<vec3>} The shadow coordinates.
  25895. */
  25896. setupShadowCoord( builder, shadowPosition ) {
  25897. return shadowPosition;
  25898. }
  25899. /**
  25900. * Overwrites the default implementation to only use point light specific
  25901. * shadow filter functions.
  25902. *
  25903. * @param {NodeBuilder} builder - A reference to the current node builder.
  25904. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25905. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25906. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25907. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25908. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25909. * @param {LightShadow} inputs.shadow - The light shadow.
  25910. * @return {Node<float>} The result node of the shadow filtering.
  25911. */
  25912. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25913. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25914. }
  25915. /**
  25916. * Overwrites the default implementation with point light specific
  25917. * rendering code.
  25918. *
  25919. * @param {NodeFrame} frame - A reference to the current node frame.
  25920. */
  25921. renderShadow( frame ) {
  25922. const { shadow, shadowMap, light } = this;
  25923. const { renderer, scene } = frame;
  25924. const shadowFrameExtents = shadow.getFrameExtents();
  25925. _shadowMapSize.copy( shadow.mapSize );
  25926. _shadowMapSize.multiply( shadowFrameExtents );
  25927. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25928. _viewportSize.copy( shadow.mapSize );
  25929. //
  25930. const previousAutoClear = renderer.autoClear;
  25931. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25932. const previousClearAlpha = renderer.getClearAlpha();
  25933. renderer.autoClear = false;
  25934. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25935. renderer.clear();
  25936. const viewportCount = shadow.getViewportCount();
  25937. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25938. const viewport = shadow.getViewport( vp );
  25939. const x = _viewportSize.x * viewport.x;
  25940. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25941. _viewport.set(
  25942. x,
  25943. y,
  25944. _viewportSize.x * viewport.z,
  25945. _viewportSize.y * viewport.w
  25946. );
  25947. shadowMap.viewport.copy( _viewport );
  25948. shadow.updateMatrices( light, vp );
  25949. renderer.render( scene, shadow.camera );
  25950. }
  25951. //
  25952. renderer.autoClear = previousAutoClear;
  25953. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25954. }
  25955. }
  25956. /**
  25957. * TSL function for creating an instance of `PointShadowNode`.
  25958. *
  25959. * @function
  25960. * @param {PointLight} light - The shadow casting point light.
  25961. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25962. * @return {PointShadowNode} The created point shadow node.
  25963. */
  25964. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25965. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25966. const lightingModel = builder.context.lightingModel;
  25967. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25968. const lightDirection = lVector.normalize();
  25969. const lightDistance = lVector.length();
  25970. const lightAttenuation = getDistanceAttenuation( {
  25971. lightDistance,
  25972. cutoffDistance,
  25973. decayExponent
  25974. } );
  25975. const lightColor = color.mul( lightAttenuation );
  25976. const reflectedLight = builder.context.reflectedLight;
  25977. lightingModel.direct( {
  25978. lightDirection,
  25979. lightColor,
  25980. reflectedLight
  25981. }, builder.stack, builder );
  25982. } );
  25983. /**
  25984. * Module for representing point lights as nodes.
  25985. *
  25986. * @augments AnalyticLightNode
  25987. */
  25988. class PointLightNode extends AnalyticLightNode {
  25989. static get type() {
  25990. return 'PointLightNode';
  25991. }
  25992. /**
  25993. * Constructs a new point light node.
  25994. *
  25995. * @param {PointLight?} [light=null] - The point light source.
  25996. */
  25997. constructor( light = null ) {
  25998. super( light );
  25999. /**
  26000. * Uniform node representing the cutoff distance.
  26001. *
  26002. * @type {UniformNode<float>}
  26003. */
  26004. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26005. /**
  26006. * Uniform node representing the decay exponent.
  26007. *
  26008. * @type {UniformNode<float>}
  26009. */
  26010. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26011. }
  26012. /**
  26013. * Overwritten to updated point light specific uniforms.
  26014. *
  26015. * @param {NodeFrame} frame - A reference to the current node frame.
  26016. */
  26017. update( frame ) {
  26018. const { light } = this;
  26019. super.update( frame );
  26020. this.cutoffDistanceNode.value = light.distance;
  26021. this.decayExponentNode.value = light.decay;
  26022. }
  26023. /**
  26024. * Overwritten to setup point light specific shadow.
  26025. *
  26026. * @return {PointShadowNode}
  26027. */
  26028. setupShadowNode() {
  26029. return pointShadow( this.light );
  26030. }
  26031. setup( builder ) {
  26032. super.setup( builder );
  26033. directPointLight( {
  26034. color: this.colorNode,
  26035. lightViewPosition: lightViewPosition( this.light ),
  26036. cutoffDistance: this.cutoffDistanceNode,
  26037. decayExponent: this.decayExponentNode
  26038. } ).append();
  26039. }
  26040. }
  26041. /** @module Procedural **/
  26042. /**
  26043. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26044. *
  26045. * @method
  26046. * @param {Node<vec2>} coord - The uv coordinates.
  26047. * @return {Node<float>} The result data.
  26048. */
  26049. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26050. const uv = coord.mul( 2.0 );
  26051. const cx = uv.x.floor();
  26052. const cy = uv.y.floor();
  26053. const result = cx.add( cy ).mod( 2.0 );
  26054. return result.sign();
  26055. } );
  26056. /** @module Shapes **/
  26057. /**
  26058. * Generates a circle based on the uv coordinates.
  26059. *
  26060. * @method
  26061. * @param {Node<vec2>} coord - The uv to generate the circle.
  26062. * @return {Node<float>} The circle shape.
  26063. */
  26064. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26065. const alpha = float( 1 ).toVar();
  26066. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26067. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26068. const dlen = float( len2.fwidth() ).toVar();
  26069. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26070. } else {
  26071. len2.greaterThan( 1.0 ).discard();
  26072. }
  26073. return alpha;
  26074. } );
  26075. // Three.js Transpiler
  26076. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26077. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26078. const f = float( f_immutable ).toVar();
  26079. const t = float( t_immutable ).toVar();
  26080. const b = bool( b_immutable ).toVar();
  26081. return select( b, t, f );
  26082. } ).setLayout( {
  26083. name: 'mx_select',
  26084. type: 'float',
  26085. inputs: [
  26086. { name: 'b', type: 'bool' },
  26087. { name: 't', type: 'float' },
  26088. { name: 'f', type: 'float' }
  26089. ]
  26090. } );
  26091. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26092. const b = bool( b_immutable ).toVar();
  26093. const val = float( val_immutable ).toVar();
  26094. return select( b, val.negate(), val );
  26095. } ).setLayout( {
  26096. name: 'mx_negate_if',
  26097. type: 'float',
  26098. inputs: [
  26099. { name: 'val', type: 'float' },
  26100. { name: 'b', type: 'bool' }
  26101. ]
  26102. } );
  26103. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26104. const x = float( x_immutable ).toVar();
  26105. return int( floor( x ) );
  26106. } ).setLayout( {
  26107. name: 'mx_floor',
  26108. type: 'int',
  26109. inputs: [
  26110. { name: 'x', type: 'float' }
  26111. ]
  26112. } );
  26113. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26114. const x = float( x_immutable ).toVar();
  26115. i.assign( mx_floor( x ) );
  26116. return x.sub( float( i ) );
  26117. } );
  26118. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26119. const t = float( t_immutable ).toVar();
  26120. const s = float( s_immutable ).toVar();
  26121. const v3 = float( v3_immutable ).toVar();
  26122. const v2 = float( v2_immutable ).toVar();
  26123. const v1 = float( v1_immutable ).toVar();
  26124. const v0 = float( v0_immutable ).toVar();
  26125. const s1 = float( sub( 1.0, s ) ).toVar();
  26126. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26127. } ).setLayout( {
  26128. name: 'mx_bilerp_0',
  26129. type: 'float',
  26130. inputs: [
  26131. { name: 'v0', type: 'float' },
  26132. { name: 'v1', type: 'float' },
  26133. { name: 'v2', type: 'float' },
  26134. { name: 'v3', type: 'float' },
  26135. { name: 's', type: 'float' },
  26136. { name: 't', type: 'float' }
  26137. ]
  26138. } );
  26139. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26140. const t = float( t_immutable ).toVar();
  26141. const s = float( s_immutable ).toVar();
  26142. const v3 = vec3( v3_immutable ).toVar();
  26143. const v2 = vec3( v2_immutable ).toVar();
  26144. const v1 = vec3( v1_immutable ).toVar();
  26145. const v0 = vec3( v0_immutable ).toVar();
  26146. const s1 = float( sub( 1.0, s ) ).toVar();
  26147. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26148. } ).setLayout( {
  26149. name: 'mx_bilerp_1',
  26150. type: 'vec3',
  26151. inputs: [
  26152. { name: 'v0', type: 'vec3' },
  26153. { name: 'v1', type: 'vec3' },
  26154. { name: 'v2', type: 'vec3' },
  26155. { name: 'v3', type: 'vec3' },
  26156. { name: 's', type: 'float' },
  26157. { name: 't', type: 'float' }
  26158. ]
  26159. } );
  26160. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26161. 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 ] ) => {
  26162. const r = float( r_immutable ).toVar();
  26163. const t = float( t_immutable ).toVar();
  26164. const s = float( s_immutable ).toVar();
  26165. const v7 = float( v7_immutable ).toVar();
  26166. const v6 = float( v6_immutable ).toVar();
  26167. const v5 = float( v5_immutable ).toVar();
  26168. const v4 = float( v4_immutable ).toVar();
  26169. const v3 = float( v3_immutable ).toVar();
  26170. const v2 = float( v2_immutable ).toVar();
  26171. const v1 = float( v1_immutable ).toVar();
  26172. const v0 = float( v0_immutable ).toVar();
  26173. const s1 = float( sub( 1.0, s ) ).toVar();
  26174. const t1 = float( sub( 1.0, t ) ).toVar();
  26175. const r1 = float( sub( 1.0, r ) ).toVar();
  26176. 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 ) ) ) ) ) );
  26177. } ).setLayout( {
  26178. name: 'mx_trilerp_0',
  26179. type: 'float',
  26180. inputs: [
  26181. { name: 'v0', type: 'float' },
  26182. { name: 'v1', type: 'float' },
  26183. { name: 'v2', type: 'float' },
  26184. { name: 'v3', type: 'float' },
  26185. { name: 'v4', type: 'float' },
  26186. { name: 'v5', type: 'float' },
  26187. { name: 'v6', type: 'float' },
  26188. { name: 'v7', type: 'float' },
  26189. { name: 's', type: 'float' },
  26190. { name: 't', type: 'float' },
  26191. { name: 'r', type: 'float' }
  26192. ]
  26193. } );
  26194. 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 ] ) => {
  26195. const r = float( r_immutable ).toVar();
  26196. const t = float( t_immutable ).toVar();
  26197. const s = float( s_immutable ).toVar();
  26198. const v7 = vec3( v7_immutable ).toVar();
  26199. const v6 = vec3( v6_immutable ).toVar();
  26200. const v5 = vec3( v5_immutable ).toVar();
  26201. const v4 = vec3( v4_immutable ).toVar();
  26202. const v3 = vec3( v3_immutable ).toVar();
  26203. const v2 = vec3( v2_immutable ).toVar();
  26204. const v1 = vec3( v1_immutable ).toVar();
  26205. const v0 = vec3( v0_immutable ).toVar();
  26206. const s1 = float( sub( 1.0, s ) ).toVar();
  26207. const t1 = float( sub( 1.0, t ) ).toVar();
  26208. const r1 = float( sub( 1.0, r ) ).toVar();
  26209. 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 ) ) ) ) ) );
  26210. } ).setLayout( {
  26211. name: 'mx_trilerp_1',
  26212. type: 'vec3',
  26213. inputs: [
  26214. { name: 'v0', type: 'vec3' },
  26215. { name: 'v1', type: 'vec3' },
  26216. { name: 'v2', type: 'vec3' },
  26217. { name: 'v3', type: 'vec3' },
  26218. { name: 'v4', type: 'vec3' },
  26219. { name: 'v5', type: 'vec3' },
  26220. { name: 'v6', type: 'vec3' },
  26221. { name: 'v7', type: 'vec3' },
  26222. { name: 's', type: 'float' },
  26223. { name: 't', type: 'float' },
  26224. { name: 'r', type: 'float' }
  26225. ]
  26226. } );
  26227. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26228. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26229. const y = float( y_immutable ).toVar();
  26230. const x = float( x_immutable ).toVar();
  26231. const hash = uint( hash_immutable ).toVar();
  26232. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26233. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26234. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26235. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26236. } ).setLayout( {
  26237. name: 'mx_gradient_float_0',
  26238. type: 'float',
  26239. inputs: [
  26240. { name: 'hash', type: 'uint' },
  26241. { name: 'x', type: 'float' },
  26242. { name: 'y', type: 'float' }
  26243. ]
  26244. } );
  26245. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26246. const z = float( z_immutable ).toVar();
  26247. const y = float( y_immutable ).toVar();
  26248. const x = float( x_immutable ).toVar();
  26249. const hash = uint( hash_immutable ).toVar();
  26250. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26251. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26252. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26253. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26254. } ).setLayout( {
  26255. name: 'mx_gradient_float_1',
  26256. type: 'float',
  26257. inputs: [
  26258. { name: 'hash', type: 'uint' },
  26259. { name: 'x', type: 'float' },
  26260. { name: 'y', type: 'float' },
  26261. { name: 'z', type: 'float' }
  26262. ]
  26263. } );
  26264. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26265. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26266. const y = float( y_immutable ).toVar();
  26267. const x = float( x_immutable ).toVar();
  26268. const hash = uvec3( hash_immutable ).toVar();
  26269. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26270. } ).setLayout( {
  26271. name: 'mx_gradient_vec3_0',
  26272. type: 'vec3',
  26273. inputs: [
  26274. { name: 'hash', type: 'uvec3' },
  26275. { name: 'x', type: 'float' },
  26276. { name: 'y', type: 'float' }
  26277. ]
  26278. } );
  26279. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26280. const z = float( z_immutable ).toVar();
  26281. const y = float( y_immutable ).toVar();
  26282. const x = float( x_immutable ).toVar();
  26283. const hash = uvec3( hash_immutable ).toVar();
  26284. 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 ) );
  26285. } ).setLayout( {
  26286. name: 'mx_gradient_vec3_1',
  26287. type: 'vec3',
  26288. inputs: [
  26289. { name: 'hash', type: 'uvec3' },
  26290. { name: 'x', type: 'float' },
  26291. { name: 'y', type: 'float' },
  26292. { name: 'z', type: 'float' }
  26293. ]
  26294. } );
  26295. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26296. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26297. const v = float( v_immutable ).toVar();
  26298. return mul( 0.6616, v );
  26299. } ).setLayout( {
  26300. name: 'mx_gradient_scale2d_0',
  26301. type: 'float',
  26302. inputs: [
  26303. { name: 'v', type: 'float' }
  26304. ]
  26305. } );
  26306. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26307. const v = float( v_immutable ).toVar();
  26308. return mul( 0.9820, v );
  26309. } ).setLayout( {
  26310. name: 'mx_gradient_scale3d_0',
  26311. type: 'float',
  26312. inputs: [
  26313. { name: 'v', type: 'float' }
  26314. ]
  26315. } );
  26316. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26317. const v = vec3( v_immutable ).toVar();
  26318. return mul( 0.6616, v );
  26319. } ).setLayout( {
  26320. name: 'mx_gradient_scale2d_1',
  26321. type: 'vec3',
  26322. inputs: [
  26323. { name: 'v', type: 'vec3' }
  26324. ]
  26325. } );
  26326. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26327. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26328. const v = vec3( v_immutable ).toVar();
  26329. return mul( 0.9820, v );
  26330. } ).setLayout( {
  26331. name: 'mx_gradient_scale3d_1',
  26332. type: 'vec3',
  26333. inputs: [
  26334. { name: 'v', type: 'vec3' }
  26335. ]
  26336. } );
  26337. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26338. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26339. const k = int( k_immutable ).toVar();
  26340. const x = uint( x_immutable ).toVar();
  26341. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26342. } ).setLayout( {
  26343. name: 'mx_rotl32',
  26344. type: 'uint',
  26345. inputs: [
  26346. { name: 'x', type: 'uint' },
  26347. { name: 'k', type: 'int' }
  26348. ]
  26349. } );
  26350. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26351. a.subAssign( c );
  26352. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26353. c.addAssign( b );
  26354. b.subAssign( a );
  26355. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26356. a.addAssign( c );
  26357. c.subAssign( b );
  26358. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26359. b.addAssign( a );
  26360. a.subAssign( c );
  26361. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26362. c.addAssign( b );
  26363. b.subAssign( a );
  26364. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26365. a.addAssign( c );
  26366. c.subAssign( b );
  26367. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26368. b.addAssign( a );
  26369. } );
  26370. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26371. const c = uint( c_immutable ).toVar();
  26372. const b = uint( b_immutable ).toVar();
  26373. const a = uint( a_immutable ).toVar();
  26374. c.bitXorAssign( b );
  26375. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26376. a.bitXorAssign( c );
  26377. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26378. b.bitXorAssign( a );
  26379. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26380. c.bitXorAssign( b );
  26381. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26382. a.bitXorAssign( c );
  26383. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26384. b.bitXorAssign( a );
  26385. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26386. c.bitXorAssign( b );
  26387. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26388. return c;
  26389. } ).setLayout( {
  26390. name: 'mx_bjfinal',
  26391. type: 'uint',
  26392. inputs: [
  26393. { name: 'a', type: 'uint' },
  26394. { name: 'b', type: 'uint' },
  26395. { name: 'c', type: 'uint' }
  26396. ]
  26397. } );
  26398. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26399. const bits = uint( bits_immutable ).toVar();
  26400. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26401. } ).setLayout( {
  26402. name: 'mx_bits_to_01',
  26403. type: 'float',
  26404. inputs: [
  26405. { name: 'bits', type: 'uint' }
  26406. ]
  26407. } );
  26408. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26409. const t = float( t_immutable ).toVar();
  26410. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26411. } ).setLayout( {
  26412. name: 'mx_fade',
  26413. type: 'float',
  26414. inputs: [
  26415. { name: 't', type: 'float' }
  26416. ]
  26417. } );
  26418. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26419. const x = int( x_immutable ).toVar();
  26420. const len = uint( uint( 1 ) ).toVar();
  26421. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26422. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26423. } ).setLayout( {
  26424. name: 'mx_hash_int_0',
  26425. type: 'uint',
  26426. inputs: [
  26427. { name: 'x', type: 'int' }
  26428. ]
  26429. } );
  26430. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26431. const y = int( y_immutable ).toVar();
  26432. const x = int( x_immutable ).toVar();
  26433. const len = uint( uint( 2 ) ).toVar();
  26434. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26435. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26436. a.addAssign( uint( x ) );
  26437. b.addAssign( uint( y ) );
  26438. return mx_bjfinal( a, b, c );
  26439. } ).setLayout( {
  26440. name: 'mx_hash_int_1',
  26441. type: 'uint',
  26442. inputs: [
  26443. { name: 'x', type: 'int' },
  26444. { name: 'y', type: 'int' }
  26445. ]
  26446. } );
  26447. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26448. const z = int( z_immutable ).toVar();
  26449. const y = int( y_immutable ).toVar();
  26450. const x = int( x_immutable ).toVar();
  26451. const len = uint( uint( 3 ) ).toVar();
  26452. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26453. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26454. a.addAssign( uint( x ) );
  26455. b.addAssign( uint( y ) );
  26456. c.addAssign( uint( z ) );
  26457. return mx_bjfinal( a, b, c );
  26458. } ).setLayout( {
  26459. name: 'mx_hash_int_2',
  26460. type: 'uint',
  26461. inputs: [
  26462. { name: 'x', type: 'int' },
  26463. { name: 'y', type: 'int' },
  26464. { name: 'z', type: 'int' }
  26465. ]
  26466. } );
  26467. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26468. const xx = int( xx_immutable ).toVar();
  26469. const z = int( z_immutable ).toVar();
  26470. const y = int( y_immutable ).toVar();
  26471. const x = int( x_immutable ).toVar();
  26472. const len = uint( uint( 4 ) ).toVar();
  26473. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26474. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26475. a.addAssign( uint( x ) );
  26476. b.addAssign( uint( y ) );
  26477. c.addAssign( uint( z ) );
  26478. mx_bjmix( a, b, c );
  26479. a.addAssign( uint( xx ) );
  26480. return mx_bjfinal( a, b, c );
  26481. } ).setLayout( {
  26482. name: 'mx_hash_int_3',
  26483. type: 'uint',
  26484. inputs: [
  26485. { name: 'x', type: 'int' },
  26486. { name: 'y', type: 'int' },
  26487. { name: 'z', type: 'int' },
  26488. { name: 'xx', type: 'int' }
  26489. ]
  26490. } );
  26491. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26492. const yy = int( yy_immutable ).toVar();
  26493. const xx = int( xx_immutable ).toVar();
  26494. const z = int( z_immutable ).toVar();
  26495. const y = int( y_immutable ).toVar();
  26496. const x = int( x_immutable ).toVar();
  26497. const len = uint( uint( 5 ) ).toVar();
  26498. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26499. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26500. a.addAssign( uint( x ) );
  26501. b.addAssign( uint( y ) );
  26502. c.addAssign( uint( z ) );
  26503. mx_bjmix( a, b, c );
  26504. a.addAssign( uint( xx ) );
  26505. b.addAssign( uint( yy ) );
  26506. return mx_bjfinal( a, b, c );
  26507. } ).setLayout( {
  26508. name: 'mx_hash_int_4',
  26509. type: 'uint',
  26510. inputs: [
  26511. { name: 'x', type: 'int' },
  26512. { name: 'y', type: 'int' },
  26513. { name: 'z', type: 'int' },
  26514. { name: 'xx', type: 'int' },
  26515. { name: 'yy', type: 'int' }
  26516. ]
  26517. } );
  26518. 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 ] );
  26519. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26520. const y = int( y_immutable ).toVar();
  26521. const x = int( x_immutable ).toVar();
  26522. const h = uint( mx_hash_int( x, y ) ).toVar();
  26523. const result = uvec3().toVar();
  26524. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26525. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26526. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26527. return result;
  26528. } ).setLayout( {
  26529. name: 'mx_hash_vec3_0',
  26530. type: 'uvec3',
  26531. inputs: [
  26532. { name: 'x', type: 'int' },
  26533. { name: 'y', type: 'int' }
  26534. ]
  26535. } );
  26536. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26537. const z = int( z_immutable ).toVar();
  26538. const y = int( y_immutable ).toVar();
  26539. const x = int( x_immutable ).toVar();
  26540. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26541. const result = uvec3().toVar();
  26542. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26543. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26544. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26545. return result;
  26546. } ).setLayout( {
  26547. name: 'mx_hash_vec3_1',
  26548. type: 'uvec3',
  26549. inputs: [
  26550. { name: 'x', type: 'int' },
  26551. { name: 'y', type: 'int' },
  26552. { name: 'z', type: 'int' }
  26553. ]
  26554. } );
  26555. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26556. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26557. const p = vec2( p_immutable ).toVar();
  26558. const X = int().toVar(), Y = int().toVar();
  26559. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26560. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26561. const u = float( mx_fade( fx ) ).toVar();
  26562. const v = float( mx_fade( fy ) ).toVar();
  26563. 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();
  26564. return mx_gradient_scale2d( result );
  26565. } ).setLayout( {
  26566. name: 'mx_perlin_noise_float_0',
  26567. type: 'float',
  26568. inputs: [
  26569. { name: 'p', type: 'vec2' }
  26570. ]
  26571. } );
  26572. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26573. const p = vec3( p_immutable ).toVar();
  26574. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26575. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26576. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26577. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26578. const u = float( mx_fade( fx ) ).toVar();
  26579. const v = float( mx_fade( fy ) ).toVar();
  26580. const w = float( mx_fade( fz ) ).toVar();
  26581. 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();
  26582. return mx_gradient_scale3d( result );
  26583. } ).setLayout( {
  26584. name: 'mx_perlin_noise_float_1',
  26585. type: 'float',
  26586. inputs: [
  26587. { name: 'p', type: 'vec3' }
  26588. ]
  26589. } );
  26590. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26591. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26592. const p = vec2( p_immutable ).toVar();
  26593. const X = int().toVar(), Y = int().toVar();
  26594. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26595. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26596. const u = float( mx_fade( fx ) ).toVar();
  26597. const v = float( mx_fade( fy ) ).toVar();
  26598. 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();
  26599. return mx_gradient_scale2d( result );
  26600. } ).setLayout( {
  26601. name: 'mx_perlin_noise_vec3_0',
  26602. type: 'vec3',
  26603. inputs: [
  26604. { name: 'p', type: 'vec2' }
  26605. ]
  26606. } );
  26607. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26608. const p = vec3( p_immutable ).toVar();
  26609. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26610. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26611. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26612. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26613. const u = float( mx_fade( fx ) ).toVar();
  26614. const v = float( mx_fade( fy ) ).toVar();
  26615. const w = float( mx_fade( fz ) ).toVar();
  26616. 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();
  26617. return mx_gradient_scale3d( result );
  26618. } ).setLayout( {
  26619. name: 'mx_perlin_noise_vec3_1',
  26620. type: 'vec3',
  26621. inputs: [
  26622. { name: 'p', type: 'vec3' }
  26623. ]
  26624. } );
  26625. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26626. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26627. const p = float( p_immutable ).toVar();
  26628. const ix = int( mx_floor( p ) ).toVar();
  26629. return mx_bits_to_01( mx_hash_int( ix ) );
  26630. } ).setLayout( {
  26631. name: 'mx_cell_noise_float_0',
  26632. type: 'float',
  26633. inputs: [
  26634. { name: 'p', type: 'float' }
  26635. ]
  26636. } );
  26637. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26638. const p = vec2( p_immutable ).toVar();
  26639. const ix = int( mx_floor( p.x ) ).toVar();
  26640. const iy = int( mx_floor( p.y ) ).toVar();
  26641. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26642. } ).setLayout( {
  26643. name: 'mx_cell_noise_float_1',
  26644. type: 'float',
  26645. inputs: [
  26646. { name: 'p', type: 'vec2' }
  26647. ]
  26648. } );
  26649. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26650. const p = vec3( p_immutable ).toVar();
  26651. const ix = int( mx_floor( p.x ) ).toVar();
  26652. const iy = int( mx_floor( p.y ) ).toVar();
  26653. const iz = int( mx_floor( p.z ) ).toVar();
  26654. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26655. } ).setLayout( {
  26656. name: 'mx_cell_noise_float_2',
  26657. type: 'float',
  26658. inputs: [
  26659. { name: 'p', type: 'vec3' }
  26660. ]
  26661. } );
  26662. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26663. const p = vec4( p_immutable ).toVar();
  26664. const ix = int( mx_floor( p.x ) ).toVar();
  26665. const iy = int( mx_floor( p.y ) ).toVar();
  26666. const iz = int( mx_floor( p.z ) ).toVar();
  26667. const iw = int( mx_floor( p.w ) ).toVar();
  26668. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26669. } ).setLayout( {
  26670. name: 'mx_cell_noise_float_3',
  26671. type: 'float',
  26672. inputs: [
  26673. { name: 'p', type: 'vec4' }
  26674. ]
  26675. } );
  26676. 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 ] );
  26677. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26678. const p = float( p_immutable ).toVar();
  26679. const ix = int( mx_floor( p ) ).toVar();
  26680. 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 ) ) ) );
  26681. } ).setLayout( {
  26682. name: 'mx_cell_noise_vec3_0',
  26683. type: 'vec3',
  26684. inputs: [
  26685. { name: 'p', type: 'float' }
  26686. ]
  26687. } );
  26688. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26689. const p = vec2( p_immutable ).toVar();
  26690. const ix = int( mx_floor( p.x ) ).toVar();
  26691. const iy = int( mx_floor( p.y ) ).toVar();
  26692. 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 ) ) ) );
  26693. } ).setLayout( {
  26694. name: 'mx_cell_noise_vec3_1',
  26695. type: 'vec3',
  26696. inputs: [
  26697. { name: 'p', type: 'vec2' }
  26698. ]
  26699. } );
  26700. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26701. const p = vec3( p_immutable ).toVar();
  26702. const ix = int( mx_floor( p.x ) ).toVar();
  26703. const iy = int( mx_floor( p.y ) ).toVar();
  26704. const iz = int( mx_floor( p.z ) ).toVar();
  26705. 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 ) ) ) );
  26706. } ).setLayout( {
  26707. name: 'mx_cell_noise_vec3_2',
  26708. type: 'vec3',
  26709. inputs: [
  26710. { name: 'p', type: 'vec3' }
  26711. ]
  26712. } );
  26713. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26714. const p = vec4( p_immutable ).toVar();
  26715. const ix = int( mx_floor( p.x ) ).toVar();
  26716. const iy = int( mx_floor( p.y ) ).toVar();
  26717. const iz = int( mx_floor( p.z ) ).toVar();
  26718. const iw = int( mx_floor( p.w ) ).toVar();
  26719. 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 ) ) ) );
  26720. } ).setLayout( {
  26721. name: 'mx_cell_noise_vec3_3',
  26722. type: 'vec3',
  26723. inputs: [
  26724. { name: 'p', type: 'vec4' }
  26725. ]
  26726. } );
  26727. 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 ] );
  26728. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26729. const diminish = float( diminish_immutable ).toVar();
  26730. const lacunarity = float( lacunarity_immutable ).toVar();
  26731. const octaves = int( octaves_immutable ).toVar();
  26732. const p = vec3( p_immutable ).toVar();
  26733. const result = float( 0.0 ).toVar();
  26734. const amplitude = float( 1.0 ).toVar();
  26735. Loop( octaves, () => {
  26736. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26737. amplitude.mulAssign( diminish );
  26738. p.mulAssign( lacunarity );
  26739. } );
  26740. return result;
  26741. } ).setLayout( {
  26742. name: 'mx_fractal_noise_float',
  26743. type: 'float',
  26744. inputs: [
  26745. { name: 'p', type: 'vec3' },
  26746. { name: 'octaves', type: 'int' },
  26747. { name: 'lacunarity', type: 'float' },
  26748. { name: 'diminish', type: 'float' }
  26749. ]
  26750. } );
  26751. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26752. const diminish = float( diminish_immutable ).toVar();
  26753. const lacunarity = float( lacunarity_immutable ).toVar();
  26754. const octaves = int( octaves_immutable ).toVar();
  26755. const p = vec3( p_immutable ).toVar();
  26756. const result = vec3( 0.0 ).toVar();
  26757. const amplitude = float( 1.0 ).toVar();
  26758. Loop( octaves, () => {
  26759. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26760. amplitude.mulAssign( diminish );
  26761. p.mulAssign( lacunarity );
  26762. } );
  26763. return result;
  26764. } ).setLayout( {
  26765. name: 'mx_fractal_noise_vec3',
  26766. type: 'vec3',
  26767. inputs: [
  26768. { name: 'p', type: 'vec3' },
  26769. { name: 'octaves', type: 'int' },
  26770. { name: 'lacunarity', type: 'float' },
  26771. { name: 'diminish', type: 'float' }
  26772. ]
  26773. } );
  26774. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26775. const diminish = float( diminish_immutable ).toVar();
  26776. const lacunarity = float( lacunarity_immutable ).toVar();
  26777. const octaves = int( octaves_immutable ).toVar();
  26778. const p = vec3( p_immutable ).toVar();
  26779. 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 ) );
  26780. } ).setLayout( {
  26781. name: 'mx_fractal_noise_vec2',
  26782. type: 'vec2',
  26783. inputs: [
  26784. { name: 'p', type: 'vec3' },
  26785. { name: 'octaves', type: 'int' },
  26786. { name: 'lacunarity', type: 'float' },
  26787. { name: 'diminish', type: 'float' }
  26788. ]
  26789. } );
  26790. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26791. const diminish = float( diminish_immutable ).toVar();
  26792. const lacunarity = float( lacunarity_immutable ).toVar();
  26793. const octaves = int( octaves_immutable ).toVar();
  26794. const p = vec3( p_immutable ).toVar();
  26795. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26796. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26797. return vec4( c, f );
  26798. } ).setLayout( {
  26799. name: 'mx_fractal_noise_vec4',
  26800. type: 'vec4',
  26801. inputs: [
  26802. { name: 'p', type: 'vec3' },
  26803. { name: 'octaves', type: 'int' },
  26804. { name: 'lacunarity', type: 'float' },
  26805. { name: 'diminish', type: 'float' }
  26806. ]
  26807. } );
  26808. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26809. const metric = int( metric_immutable ).toVar();
  26810. const jitter = float( jitter_immutable ).toVar();
  26811. const yoff = int( yoff_immutable ).toVar();
  26812. const xoff = int( xoff_immutable ).toVar();
  26813. const y = int( y_immutable ).toVar();
  26814. const x = int( x_immutable ).toVar();
  26815. const p = vec2( p_immutable ).toVar();
  26816. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26817. const off = vec2( tmp.x, tmp.y ).toVar();
  26818. off.subAssign( 0.5 );
  26819. off.mulAssign( jitter );
  26820. off.addAssign( 0.5 );
  26821. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26822. const diff = vec2( cellpos.sub( p ) ).toVar();
  26823. If( metric.equal( int( 2 ) ), () => {
  26824. return abs( diff.x ).add( abs( diff.y ) );
  26825. } );
  26826. If( metric.equal( int( 3 ) ), () => {
  26827. return max$1( abs( diff.x ), abs( diff.y ) );
  26828. } );
  26829. return dot( diff, diff );
  26830. } ).setLayout( {
  26831. name: 'mx_worley_distance_0',
  26832. type: 'float',
  26833. inputs: [
  26834. { name: 'p', type: 'vec2' },
  26835. { name: 'x', type: 'int' },
  26836. { name: 'y', type: 'int' },
  26837. { name: 'xoff', type: 'int' },
  26838. { name: 'yoff', type: 'int' },
  26839. { name: 'jitter', type: 'float' },
  26840. { name: 'metric', type: 'int' }
  26841. ]
  26842. } );
  26843. 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 ] ) => {
  26844. const metric = int( metric_immutable ).toVar();
  26845. const jitter = float( jitter_immutable ).toVar();
  26846. const zoff = int( zoff_immutable ).toVar();
  26847. const yoff = int( yoff_immutable ).toVar();
  26848. const xoff = int( xoff_immutable ).toVar();
  26849. const z = int( z_immutable ).toVar();
  26850. const y = int( y_immutable ).toVar();
  26851. const x = int( x_immutable ).toVar();
  26852. const p = vec3( p_immutable ).toVar();
  26853. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26854. off.subAssign( 0.5 );
  26855. off.mulAssign( jitter );
  26856. off.addAssign( 0.5 );
  26857. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26858. const diff = vec3( cellpos.sub( p ) ).toVar();
  26859. If( metric.equal( int( 2 ) ), () => {
  26860. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26861. } );
  26862. If( metric.equal( int( 3 ) ), () => {
  26863. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26864. } );
  26865. return dot( diff, diff );
  26866. } ).setLayout( {
  26867. name: 'mx_worley_distance_1',
  26868. type: 'float',
  26869. inputs: [
  26870. { name: 'p', type: 'vec3' },
  26871. { name: 'x', type: 'int' },
  26872. { name: 'y', type: 'int' },
  26873. { name: 'z', type: 'int' },
  26874. { name: 'xoff', type: 'int' },
  26875. { name: 'yoff', type: 'int' },
  26876. { name: 'zoff', type: 'int' },
  26877. { name: 'jitter', type: 'float' },
  26878. { name: 'metric', type: 'int' }
  26879. ]
  26880. } );
  26881. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26882. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26883. const metric = int( metric_immutable ).toVar();
  26884. const jitter = float( jitter_immutable ).toVar();
  26885. const p = vec2( p_immutable ).toVar();
  26886. const X = int().toVar(), Y = int().toVar();
  26887. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26888. const sqdist = float( 1e6 ).toVar();
  26889. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26890. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26891. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26892. sqdist.assign( min$1( sqdist, dist ) );
  26893. } );
  26894. } );
  26895. If( metric.equal( int( 0 ) ), () => {
  26896. sqdist.assign( sqrt( sqdist ) );
  26897. } );
  26898. return sqdist;
  26899. } ).setLayout( {
  26900. name: 'mx_worley_noise_float_0',
  26901. type: 'float',
  26902. inputs: [
  26903. { name: 'p', type: 'vec2' },
  26904. { name: 'jitter', type: 'float' },
  26905. { name: 'metric', type: 'int' }
  26906. ]
  26907. } );
  26908. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26909. const metric = int( metric_immutable ).toVar();
  26910. const jitter = float( jitter_immutable ).toVar();
  26911. const p = vec2( p_immutable ).toVar();
  26912. const X = int().toVar(), Y = int().toVar();
  26913. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26914. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26915. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26916. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26917. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26918. If( dist.lessThan( sqdist.x ), () => {
  26919. sqdist.y.assign( sqdist.x );
  26920. sqdist.x.assign( dist );
  26921. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26922. sqdist.y.assign( dist );
  26923. } );
  26924. } );
  26925. } );
  26926. If( metric.equal( int( 0 ) ), () => {
  26927. sqdist.assign( sqrt( sqdist ) );
  26928. } );
  26929. return sqdist;
  26930. } ).setLayout( {
  26931. name: 'mx_worley_noise_vec2_0',
  26932. type: 'vec2',
  26933. inputs: [
  26934. { name: 'p', type: 'vec2' },
  26935. { name: 'jitter', type: 'float' },
  26936. { name: 'metric', type: 'int' }
  26937. ]
  26938. } );
  26939. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26940. const metric = int( metric_immutable ).toVar();
  26941. const jitter = float( jitter_immutable ).toVar();
  26942. const p = vec2( p_immutable ).toVar();
  26943. const X = int().toVar(), Y = int().toVar();
  26944. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26945. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26946. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26947. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26948. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26949. If( dist.lessThan( sqdist.x ), () => {
  26950. sqdist.z.assign( sqdist.y );
  26951. sqdist.y.assign( sqdist.x );
  26952. sqdist.x.assign( dist );
  26953. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26954. sqdist.z.assign( sqdist.y );
  26955. sqdist.y.assign( dist );
  26956. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26957. sqdist.z.assign( dist );
  26958. } );
  26959. } );
  26960. } );
  26961. If( metric.equal( int( 0 ) ), () => {
  26962. sqdist.assign( sqrt( sqdist ) );
  26963. } );
  26964. return sqdist;
  26965. } ).setLayout( {
  26966. name: 'mx_worley_noise_vec3_0',
  26967. type: 'vec3',
  26968. inputs: [
  26969. { name: 'p', type: 'vec2' },
  26970. { name: 'jitter', type: 'float' },
  26971. { name: 'metric', type: 'int' }
  26972. ]
  26973. } );
  26974. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26975. const metric = int( metric_immutable ).toVar();
  26976. const jitter = float( jitter_immutable ).toVar();
  26977. const p = vec3( p_immutable ).toVar();
  26978. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26979. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26980. const sqdist = float( 1e6 ).toVar();
  26981. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26982. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26983. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26984. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26985. sqdist.assign( min$1( sqdist, dist ) );
  26986. } );
  26987. } );
  26988. } );
  26989. If( metric.equal( int( 0 ) ), () => {
  26990. sqdist.assign( sqrt( sqdist ) );
  26991. } );
  26992. return sqdist;
  26993. } ).setLayout( {
  26994. name: 'mx_worley_noise_float_1',
  26995. type: 'float',
  26996. inputs: [
  26997. { name: 'p', type: 'vec3' },
  26998. { name: 'jitter', type: 'float' },
  26999. { name: 'metric', type: 'int' }
  27000. ]
  27001. } );
  27002. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27003. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27004. const metric = int( metric_immutable ).toVar();
  27005. const jitter = float( jitter_immutable ).toVar();
  27006. const p = vec3( p_immutable ).toVar();
  27007. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27008. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27009. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27010. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27011. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27012. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27013. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27014. If( dist.lessThan( sqdist.x ), () => {
  27015. sqdist.y.assign( sqdist.x );
  27016. sqdist.x.assign( dist );
  27017. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27018. sqdist.y.assign( dist );
  27019. } );
  27020. } );
  27021. } );
  27022. } );
  27023. If( metric.equal( int( 0 ) ), () => {
  27024. sqdist.assign( sqrt( sqdist ) );
  27025. } );
  27026. return sqdist;
  27027. } ).setLayout( {
  27028. name: 'mx_worley_noise_vec2_1',
  27029. type: 'vec2',
  27030. inputs: [
  27031. { name: 'p', type: 'vec3' },
  27032. { name: 'jitter', type: 'float' },
  27033. { name: 'metric', type: 'int' }
  27034. ]
  27035. } );
  27036. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27037. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27038. const metric = int( metric_immutable ).toVar();
  27039. const jitter = float( jitter_immutable ).toVar();
  27040. const p = vec3( p_immutable ).toVar();
  27041. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27042. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27043. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27044. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27045. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27046. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27047. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27048. If( dist.lessThan( sqdist.x ), () => {
  27049. sqdist.z.assign( sqdist.y );
  27050. sqdist.y.assign( sqdist.x );
  27051. sqdist.x.assign( dist );
  27052. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27053. sqdist.z.assign( sqdist.y );
  27054. sqdist.y.assign( dist );
  27055. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27056. sqdist.z.assign( dist );
  27057. } );
  27058. } );
  27059. } );
  27060. } );
  27061. If( metric.equal( int( 0 ) ), () => {
  27062. sqdist.assign( sqrt( sqdist ) );
  27063. } );
  27064. return sqdist;
  27065. } ).setLayout( {
  27066. name: 'mx_worley_noise_vec3_1',
  27067. type: 'vec3',
  27068. inputs: [
  27069. { name: 'p', type: 'vec3' },
  27070. { name: 'jitter', type: 'float' },
  27071. { name: 'metric', type: 'int' }
  27072. ]
  27073. } );
  27074. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27075. // Three.js Transpiler
  27076. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27077. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27078. const s = hsv.y;
  27079. const v = hsv.z;
  27080. const result = vec3().toVar();
  27081. If( s.lessThan( 0.0001 ), () => {
  27082. result.assign( vec3( v, v, v ) );
  27083. } ).Else( () => {
  27084. let h = hsv.x;
  27085. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27086. const hi = int( trunc( h ) );
  27087. const f = h.sub( float( hi ) );
  27088. const p = v.mul( s.oneMinus() );
  27089. const q = v.mul( s.mul( f ).oneMinus() );
  27090. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27091. If( hi.equal( int( 0 ) ), () => {
  27092. result.assign( vec3( v, t, p ) );
  27093. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27094. result.assign( vec3( q, v, p ) );
  27095. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27096. result.assign( vec3( p, v, t ) );
  27097. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27098. result.assign( vec3( p, q, v ) );
  27099. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27100. result.assign( vec3( t, p, v ) );
  27101. } ).Else( () => {
  27102. result.assign( vec3( v, p, q ) );
  27103. } );
  27104. } );
  27105. return result;
  27106. } ).setLayout( {
  27107. name: 'mx_hsvtorgb',
  27108. type: 'vec3',
  27109. inputs: [
  27110. { name: 'hsv', type: 'vec3' }
  27111. ]
  27112. } );
  27113. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27114. const c = vec3( c_immutable ).toVar();
  27115. const r = float( c.x ).toVar();
  27116. const g = float( c.y ).toVar();
  27117. const b = float( c.z ).toVar();
  27118. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27119. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27120. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27121. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27122. v.assign( maxcomp );
  27123. If( maxcomp.greaterThan( 0.0 ), () => {
  27124. s.assign( delta.div( maxcomp ) );
  27125. } ).Else( () => {
  27126. s.assign( 0.0 );
  27127. } );
  27128. If( s.lessThanEqual( 0.0 ), () => {
  27129. h.assign( 0.0 );
  27130. } ).Else( () => {
  27131. If( r.greaterThanEqual( maxcomp ), () => {
  27132. h.assign( g.sub( b ).div( delta ) );
  27133. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27134. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27135. } ).Else( () => {
  27136. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27137. } );
  27138. h.mulAssign( 1.0 / 6.0 );
  27139. If( h.lessThan( 0.0 ), () => {
  27140. h.addAssign( 1.0 );
  27141. } );
  27142. } );
  27143. return vec3( h, s, v );
  27144. } ).setLayout( {
  27145. name: 'mx_rgbtohsv',
  27146. type: 'vec3',
  27147. inputs: [
  27148. { name: 'c', type: 'vec3' }
  27149. ]
  27150. } );
  27151. // Three.js Transpiler
  27152. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27153. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27154. const color = vec3( color_immutable ).toVar();
  27155. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27156. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27157. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27158. return mix( linSeg, powSeg, isAbove );
  27159. } ).setLayout( {
  27160. name: 'mx_srgb_texture_to_lin_rec709',
  27161. type: 'vec3',
  27162. inputs: [
  27163. { name: 'color', type: 'vec3' }
  27164. ]
  27165. } );
  27166. const mx_aastep = ( threshold, value ) => {
  27167. threshold = float( threshold );
  27168. value = float( value );
  27169. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27170. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27171. };
  27172. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27173. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27174. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27175. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27176. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27177. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27178. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27179. const mx_safepower = ( in1, in2 = 1 ) => {
  27180. in1 = float( in1 );
  27181. return in1.abs().pow( in2 ).mul( in1.sign() );
  27182. };
  27183. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27184. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27185. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27186. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27187. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27188. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27189. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27190. return noise_vec4.mul( amplitude ).add( pivot );
  27191. };
  27192. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27193. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27194. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27195. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27196. 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 );
  27197. 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 );
  27198. 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 );
  27199. 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 );
  27200. /** @module getParallaxCorrectNormal **/
  27201. /**
  27202. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27203. *
  27204. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27205. *
  27206. * ```js
  27207. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27208. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27209. * ```
  27210. * @function
  27211. * @param {Node<vec3>} normal - The normal to correct.
  27212. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27213. * @param {Node<vec3>} cubePos - The cube position.
  27214. * @return {Node<vec3>} The parallax corrected normal.
  27215. */
  27216. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27217. const nDir = normalize( normal ).toVar( 'nDir' );
  27218. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27219. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27220. const rbminmax = vec3().toVar( 'rbminmax' );
  27221. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27222. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27223. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27224. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27225. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27226. return boxIntersection.sub( cubePos );
  27227. } );
  27228. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27229. // normal is assumed to have unit length
  27230. const x = normal.x, y = normal.y, z = normal.z;
  27231. // band 0
  27232. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27233. // band 1
  27234. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27235. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27236. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27237. // band 2
  27238. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27239. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27240. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27241. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27242. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27243. return result;
  27244. } );
  27245. // constants
  27246. var TSL = /*#__PURE__*/Object.freeze({
  27247. __proto__: null,
  27248. BRDF_GGX: BRDF_GGX,
  27249. BRDF_Lambert: BRDF_Lambert,
  27250. BasicShadowFilter: BasicShadowFilter,
  27251. Break: Break,
  27252. Const: Const,
  27253. Continue: Continue,
  27254. DFGApprox: DFGApprox,
  27255. D_GGX: D_GGX,
  27256. Discard: Discard,
  27257. EPSILON: EPSILON,
  27258. F_Schlick: F_Schlick,
  27259. Fn: Fn,
  27260. INFINITY: INFINITY,
  27261. If: If,
  27262. Loop: Loop,
  27263. NodeAccess: NodeAccess,
  27264. NodeShaderStage: NodeShaderStage,
  27265. NodeType: NodeType,
  27266. NodeUpdateType: NodeUpdateType,
  27267. PCFShadowFilter: PCFShadowFilter,
  27268. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27269. PI: PI,
  27270. PI2: PI2,
  27271. Return: Return,
  27272. Schlick_to_F0: Schlick_to_F0,
  27273. ScriptableNodeResources: ScriptableNodeResources,
  27274. ShaderNode: ShaderNode,
  27275. TBNViewMatrix: TBNViewMatrix,
  27276. VSMShadowFilter: VSMShadowFilter,
  27277. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27278. Var: Var,
  27279. abs: abs,
  27280. acesFilmicToneMapping: acesFilmicToneMapping,
  27281. acos: acos,
  27282. add: add,
  27283. addMethodChaining: addMethodChaining,
  27284. addNodeElement: addNodeElement,
  27285. agxToneMapping: agxToneMapping,
  27286. all: all,
  27287. alphaT: alphaT,
  27288. and: and,
  27289. anisotropy: anisotropy,
  27290. anisotropyB: anisotropyB,
  27291. anisotropyT: anisotropyT,
  27292. any: any,
  27293. append: append,
  27294. arrayBuffer: arrayBuffer,
  27295. asin: asin,
  27296. assign: assign,
  27297. atan: atan,
  27298. atan2: atan2,
  27299. atomicAdd: atomicAdd,
  27300. atomicAnd: atomicAnd,
  27301. atomicFunc: atomicFunc,
  27302. atomicMax: atomicMax,
  27303. atomicMin: atomicMin,
  27304. atomicOr: atomicOr,
  27305. atomicStore: atomicStore,
  27306. atomicSub: atomicSub,
  27307. atomicXor: atomicXor,
  27308. attenuationColor: attenuationColor,
  27309. attenuationDistance: attenuationDistance,
  27310. attribute: attribute,
  27311. attributeArray: attributeArray,
  27312. backgroundBlurriness: backgroundBlurriness,
  27313. backgroundIntensity: backgroundIntensity,
  27314. backgroundRotation: backgroundRotation,
  27315. batch: batch,
  27316. billboarding: billboarding,
  27317. bitAnd: bitAnd,
  27318. bitNot: bitNot,
  27319. bitOr: bitOr,
  27320. bitXor: bitXor,
  27321. bitangentGeometry: bitangentGeometry,
  27322. bitangentLocal: bitangentLocal,
  27323. bitangentView: bitangentView,
  27324. bitangentWorld: bitangentWorld,
  27325. bitcast: bitcast,
  27326. blendBurn: blendBurn,
  27327. blendColor: blendColor,
  27328. blendDodge: blendDodge,
  27329. blendOverlay: blendOverlay,
  27330. blendScreen: blendScreen,
  27331. blur: blur,
  27332. bool: bool,
  27333. buffer: buffer,
  27334. bufferAttribute: bufferAttribute,
  27335. bumpMap: bumpMap,
  27336. burn: burn,
  27337. bvec2: bvec2,
  27338. bvec3: bvec3,
  27339. bvec4: bvec4,
  27340. bypass: bypass,
  27341. cache: cache,
  27342. call: call,
  27343. cameraFar: cameraFar,
  27344. cameraIndex: cameraIndex,
  27345. cameraNear: cameraNear,
  27346. cameraNormalMatrix: cameraNormalMatrix,
  27347. cameraPosition: cameraPosition,
  27348. cameraProjectionMatrix: cameraProjectionMatrix,
  27349. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27350. cameraViewMatrix: cameraViewMatrix,
  27351. cameraWorldMatrix: cameraWorldMatrix,
  27352. cbrt: cbrt,
  27353. cdl: cdl,
  27354. ceil: ceil,
  27355. checker: checker,
  27356. cineonToneMapping: cineonToneMapping,
  27357. clamp: clamp,
  27358. clearcoat: clearcoat,
  27359. clearcoatRoughness: clearcoatRoughness,
  27360. code: code,
  27361. color: color,
  27362. colorSpaceToWorking: colorSpaceToWorking,
  27363. colorToDirection: colorToDirection,
  27364. compute: compute,
  27365. cond: cond,
  27366. context: context,
  27367. convert: convert,
  27368. convertColorSpace: convertColorSpace,
  27369. convertToTexture: convertToTexture,
  27370. cos: cos,
  27371. cross: cross,
  27372. cubeTexture: cubeTexture,
  27373. dFdx: dFdx,
  27374. dFdy: dFdy,
  27375. dashSize: dashSize,
  27376. defaultBuildStages: defaultBuildStages,
  27377. defaultShaderStages: defaultShaderStages,
  27378. defined: defined,
  27379. degrees: degrees,
  27380. deltaTime: deltaTime,
  27381. densityFog: densityFog,
  27382. densityFogFactor: densityFogFactor,
  27383. depth: depth,
  27384. depthPass: depthPass,
  27385. difference: difference,
  27386. diffuseColor: diffuseColor,
  27387. directPointLight: directPointLight,
  27388. directionToColor: directionToColor,
  27389. dispersion: dispersion,
  27390. distance: distance,
  27391. div: div,
  27392. dodge: dodge,
  27393. dot: dot,
  27394. drawIndex: drawIndex,
  27395. dynamicBufferAttribute: dynamicBufferAttribute,
  27396. element: element,
  27397. emissive: emissive,
  27398. equal: equal,
  27399. equals: equals,
  27400. equirectUV: equirectUV,
  27401. exp: exp,
  27402. exp2: exp2,
  27403. expression: expression,
  27404. faceDirection: faceDirection,
  27405. faceForward: faceForward,
  27406. faceforward: faceforward,
  27407. float: float,
  27408. floor: floor,
  27409. fog: fog,
  27410. fract: fract,
  27411. frameGroup: frameGroup,
  27412. frameId: frameId,
  27413. frontFacing: frontFacing,
  27414. fwidth: fwidth,
  27415. gain: gain,
  27416. gapSize: gapSize,
  27417. getConstNodeType: getConstNodeType,
  27418. getCurrentStack: getCurrentStack,
  27419. getDirection: getDirection,
  27420. getDistanceAttenuation: getDistanceAttenuation,
  27421. getGeometryRoughness: getGeometryRoughness,
  27422. getNormalFromDepth: getNormalFromDepth,
  27423. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27424. getRoughness: getRoughness,
  27425. getScreenPosition: getScreenPosition,
  27426. getShIrradianceAt: getShIrradianceAt,
  27427. getTextureIndex: getTextureIndex,
  27428. getViewPosition: getViewPosition,
  27429. globalId: globalId,
  27430. glsl: glsl,
  27431. glslFn: glslFn,
  27432. grayscale: grayscale,
  27433. greaterThan: greaterThan,
  27434. greaterThanEqual: greaterThanEqual,
  27435. hash: hash,
  27436. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27437. highpModelViewMatrix: highpModelViewMatrix,
  27438. hue: hue,
  27439. instance: instance,
  27440. instanceIndex: instanceIndex,
  27441. instancedArray: instancedArray,
  27442. instancedBufferAttribute: instancedBufferAttribute,
  27443. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27444. instancedMesh: instancedMesh,
  27445. int: int,
  27446. inverseSqrt: inverseSqrt,
  27447. inversesqrt: inversesqrt,
  27448. invocationLocalIndex: invocationLocalIndex,
  27449. invocationSubgroupIndex: invocationSubgroupIndex,
  27450. ior: ior,
  27451. iridescence: iridescence,
  27452. iridescenceIOR: iridescenceIOR,
  27453. iridescenceThickness: iridescenceThickness,
  27454. ivec2: ivec2,
  27455. ivec3: ivec3,
  27456. ivec4: ivec4,
  27457. js: js,
  27458. label: label,
  27459. length: length,
  27460. lengthSq: lengthSq,
  27461. lessThan: lessThan,
  27462. lessThanEqual: lessThanEqual,
  27463. lightPosition: lightPosition,
  27464. lightProjectionUV: lightProjectionUV,
  27465. lightShadowMatrix: lightShadowMatrix,
  27466. lightTargetDirection: lightTargetDirection,
  27467. lightTargetPosition: lightTargetPosition,
  27468. lightViewPosition: lightViewPosition,
  27469. lightingContext: lightingContext,
  27470. lights: lights,
  27471. linearDepth: linearDepth,
  27472. linearToneMapping: linearToneMapping,
  27473. localId: localId,
  27474. log: log,
  27475. log2: log2,
  27476. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27477. loop: loop,
  27478. luminance: luminance,
  27479. mat2: mat2,
  27480. mat3: mat3,
  27481. mat4: mat4,
  27482. matcapUV: matcapUV,
  27483. materialAO: materialAO,
  27484. materialAlphaTest: materialAlphaTest,
  27485. materialAnisotropy: materialAnisotropy,
  27486. materialAnisotropyVector: materialAnisotropyVector,
  27487. materialAttenuationColor: materialAttenuationColor,
  27488. materialAttenuationDistance: materialAttenuationDistance,
  27489. materialClearcoat: materialClearcoat,
  27490. materialClearcoatNormal: materialClearcoatNormal,
  27491. materialClearcoatRoughness: materialClearcoatRoughness,
  27492. materialColor: materialColor,
  27493. materialDispersion: materialDispersion,
  27494. materialEmissive: materialEmissive,
  27495. materialIOR: materialIOR,
  27496. materialIridescence: materialIridescence,
  27497. materialIridescenceIOR: materialIridescenceIOR,
  27498. materialIridescenceThickness: materialIridescenceThickness,
  27499. materialLightMap: materialLightMap,
  27500. materialLineDashOffset: materialLineDashOffset,
  27501. materialLineDashSize: materialLineDashSize,
  27502. materialLineGapSize: materialLineGapSize,
  27503. materialLineScale: materialLineScale,
  27504. materialLineWidth: materialLineWidth,
  27505. materialMetalness: materialMetalness,
  27506. materialNormal: materialNormal,
  27507. materialOpacity: materialOpacity,
  27508. materialPointSize: materialPointSize,
  27509. materialReference: materialReference,
  27510. materialReflectivity: materialReflectivity,
  27511. materialRefractionRatio: materialRefractionRatio,
  27512. materialRotation: materialRotation,
  27513. materialRoughness: materialRoughness,
  27514. materialSheen: materialSheen,
  27515. materialSheenRoughness: materialSheenRoughness,
  27516. materialShininess: materialShininess,
  27517. materialSpecular: materialSpecular,
  27518. materialSpecularColor: materialSpecularColor,
  27519. materialSpecularIntensity: materialSpecularIntensity,
  27520. materialSpecularStrength: materialSpecularStrength,
  27521. materialThickness: materialThickness,
  27522. materialTransmission: materialTransmission,
  27523. max: max$1,
  27524. maxMipLevel: maxMipLevel,
  27525. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27526. metalness: metalness,
  27527. min: min$1,
  27528. mix: mix,
  27529. mixElement: mixElement,
  27530. mod: mod,
  27531. modInt: modInt,
  27532. modelDirection: modelDirection,
  27533. modelNormalMatrix: modelNormalMatrix,
  27534. modelPosition: modelPosition,
  27535. modelScale: modelScale,
  27536. modelViewMatrix: modelViewMatrix,
  27537. modelViewPosition: modelViewPosition,
  27538. modelViewProjection: modelViewProjection,
  27539. modelWorldMatrix: modelWorldMatrix,
  27540. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27541. morphReference: morphReference,
  27542. mrt: mrt,
  27543. mul: mul,
  27544. mx_aastep: mx_aastep,
  27545. mx_cell_noise_float: mx_cell_noise_float,
  27546. mx_contrast: mx_contrast,
  27547. mx_fractal_noise_float: mx_fractal_noise_float,
  27548. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27549. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27550. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27551. mx_hsvtorgb: mx_hsvtorgb,
  27552. mx_noise_float: mx_noise_float,
  27553. mx_noise_vec3: mx_noise_vec3,
  27554. mx_noise_vec4: mx_noise_vec4,
  27555. mx_ramplr: mx_ramplr,
  27556. mx_ramptb: mx_ramptb,
  27557. mx_rgbtohsv: mx_rgbtohsv,
  27558. mx_safepower: mx_safepower,
  27559. mx_splitlr: mx_splitlr,
  27560. mx_splittb: mx_splittb,
  27561. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27562. mx_transform_uv: mx_transform_uv,
  27563. mx_worley_noise_float: mx_worley_noise_float,
  27564. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27565. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27566. negate: negate,
  27567. neutralToneMapping: neutralToneMapping,
  27568. nodeArray: nodeArray,
  27569. nodeImmutable: nodeImmutable,
  27570. nodeObject: nodeObject,
  27571. nodeObjects: nodeObjects,
  27572. nodeProxy: nodeProxy,
  27573. normalFlat: normalFlat,
  27574. normalGeometry: normalGeometry,
  27575. normalLocal: normalLocal,
  27576. normalMap: normalMap,
  27577. normalView: normalView,
  27578. normalWorld: normalWorld,
  27579. normalize: normalize,
  27580. not: not,
  27581. notEqual: notEqual,
  27582. numWorkgroups: numWorkgroups,
  27583. objectDirection: objectDirection,
  27584. objectGroup: objectGroup,
  27585. objectPosition: objectPosition,
  27586. objectScale: objectScale,
  27587. objectViewPosition: objectViewPosition,
  27588. objectWorldMatrix: objectWorldMatrix,
  27589. oneMinus: oneMinus,
  27590. or: or,
  27591. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27592. oscSawtooth: oscSawtooth,
  27593. oscSine: oscSine,
  27594. oscSquare: oscSquare,
  27595. oscTriangle: oscTriangle,
  27596. output: output,
  27597. outputStruct: outputStruct,
  27598. overlay: overlay,
  27599. overloadingFn: overloadingFn,
  27600. parabola: parabola,
  27601. parallaxDirection: parallaxDirection,
  27602. parallaxUV: parallaxUV,
  27603. parameter: parameter,
  27604. pass: pass,
  27605. passTexture: passTexture,
  27606. pcurve: pcurve,
  27607. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27608. pmremTexture: pmremTexture,
  27609. pointUV: pointUV,
  27610. pointWidth: pointWidth,
  27611. positionGeometry: positionGeometry,
  27612. positionLocal: positionLocal,
  27613. positionPrevious: positionPrevious,
  27614. positionView: positionView,
  27615. positionViewDirection: positionViewDirection,
  27616. positionWorld: positionWorld,
  27617. positionWorldDirection: positionWorldDirection,
  27618. posterize: posterize,
  27619. pow: pow,
  27620. pow2: pow2,
  27621. pow3: pow3,
  27622. pow4: pow4,
  27623. property: property,
  27624. radians: radians,
  27625. rand: rand,
  27626. range: range,
  27627. rangeFog: rangeFog,
  27628. rangeFogFactor: rangeFogFactor,
  27629. reciprocal: reciprocal,
  27630. reference: reference,
  27631. referenceBuffer: referenceBuffer,
  27632. reflect: reflect,
  27633. reflectVector: reflectVector,
  27634. reflectView: reflectView,
  27635. reflector: reflector,
  27636. refract: refract,
  27637. refractVector: refractVector,
  27638. refractView: refractView,
  27639. reinhardToneMapping: reinhardToneMapping,
  27640. remainder: remainder,
  27641. remap: remap,
  27642. remapClamp: remapClamp,
  27643. renderGroup: renderGroup,
  27644. renderOutput: renderOutput,
  27645. rendererReference: rendererReference,
  27646. rotate: rotate,
  27647. rotateUV: rotateUV,
  27648. roughness: roughness,
  27649. round: round,
  27650. rtt: rtt,
  27651. sRGBTransferEOTF: sRGBTransferEOTF,
  27652. sRGBTransferOETF: sRGBTransferOETF,
  27653. sampler: sampler,
  27654. saturate: saturate,
  27655. saturation: saturation,
  27656. screen: screen,
  27657. screenCoordinate: screenCoordinate,
  27658. screenSize: screenSize,
  27659. screenUV: screenUV,
  27660. scriptable: scriptable,
  27661. scriptableValue: scriptableValue,
  27662. select: select,
  27663. setCurrentStack: setCurrentStack,
  27664. shaderStages: shaderStages,
  27665. shadow: shadow,
  27666. shadowPositionWorld: shadowPositionWorld,
  27667. shapeCircle: shapeCircle,
  27668. sharedUniformGroup: sharedUniformGroup,
  27669. sheen: sheen,
  27670. sheenRoughness: sheenRoughness,
  27671. shiftLeft: shiftLeft,
  27672. shiftRight: shiftRight,
  27673. shininess: shininess,
  27674. sign: sign,
  27675. sin: sin,
  27676. sinc: sinc,
  27677. skinning: skinning,
  27678. skinningReference: skinningReference,
  27679. smoothstep: smoothstep,
  27680. smoothstepElement: smoothstepElement,
  27681. specularColor: specularColor,
  27682. specularF90: specularF90,
  27683. spherizeUV: spherizeUV,
  27684. split: split,
  27685. spritesheetUV: spritesheetUV,
  27686. sqrt: sqrt,
  27687. stack: stack,
  27688. step: step,
  27689. storage: storage,
  27690. storageBarrier: storageBarrier,
  27691. storageObject: storageObject,
  27692. storageTexture: storageTexture,
  27693. string: string,
  27694. sub: sub,
  27695. subgroupIndex: subgroupIndex,
  27696. subgroupSize: subgroupSize,
  27697. tan: tan,
  27698. tangentGeometry: tangentGeometry,
  27699. tangentLocal: tangentLocal,
  27700. tangentView: tangentView,
  27701. tangentWorld: tangentWorld,
  27702. temp: temp,
  27703. texture: texture,
  27704. texture3D: texture3D,
  27705. textureBarrier: textureBarrier,
  27706. textureBicubic: textureBicubic,
  27707. textureCubeUV: textureCubeUV,
  27708. textureLoad: textureLoad,
  27709. textureSize: textureSize,
  27710. textureStore: textureStore,
  27711. thickness: thickness,
  27712. time: time,
  27713. timerDelta: timerDelta,
  27714. timerGlobal: timerGlobal,
  27715. timerLocal: timerLocal,
  27716. toOutputColorSpace: toOutputColorSpace,
  27717. toWorkingColorSpace: toWorkingColorSpace,
  27718. toneMapping: toneMapping,
  27719. toneMappingExposure: toneMappingExposure,
  27720. toonOutlinePass: toonOutlinePass,
  27721. transformDirection: transformDirection,
  27722. transformNormal: transformNormal,
  27723. transformNormalToView: transformNormalToView,
  27724. transformedBentNormalView: transformedBentNormalView,
  27725. transformedBitangentView: transformedBitangentView,
  27726. transformedBitangentWorld: transformedBitangentWorld,
  27727. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27728. transformedNormalView: transformedNormalView,
  27729. transformedNormalWorld: transformedNormalWorld,
  27730. transformedTangentView: transformedTangentView,
  27731. transformedTangentWorld: transformedTangentWorld,
  27732. transmission: transmission,
  27733. transpose: transpose,
  27734. triNoise3D: triNoise3D,
  27735. triplanarTexture: triplanarTexture,
  27736. triplanarTextures: triplanarTextures,
  27737. trunc: trunc,
  27738. tslFn: tslFn,
  27739. uint: uint,
  27740. uniform: uniform,
  27741. uniformArray: uniformArray,
  27742. uniformGroup: uniformGroup,
  27743. uniforms: uniforms,
  27744. userData: userData,
  27745. uv: uv,
  27746. uvec2: uvec2,
  27747. uvec3: uvec3,
  27748. uvec4: uvec4,
  27749. varying: varying,
  27750. varyingProperty: varyingProperty,
  27751. vec2: vec2,
  27752. vec3: vec3,
  27753. vec4: vec4,
  27754. vectorComponents: vectorComponents,
  27755. velocity: velocity,
  27756. vertexColor: vertexColor,
  27757. vertexIndex: vertexIndex,
  27758. vertexStage: vertexStage,
  27759. vibrance: vibrance,
  27760. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27761. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27762. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27763. viewport: viewport,
  27764. viewportBottomLeft: viewportBottomLeft,
  27765. viewportCoordinate: viewportCoordinate,
  27766. viewportDepthTexture: viewportDepthTexture,
  27767. viewportLinearDepth: viewportLinearDepth,
  27768. viewportMipTexture: viewportMipTexture,
  27769. viewportResolution: viewportResolution,
  27770. viewportSafeUV: viewportSafeUV,
  27771. viewportSharedTexture: viewportSharedTexture,
  27772. viewportSize: viewportSize,
  27773. viewportTexture: viewportTexture,
  27774. viewportTopLeft: viewportTopLeft,
  27775. viewportUV: viewportUV,
  27776. wgsl: wgsl,
  27777. wgslFn: wgslFn,
  27778. workgroupArray: workgroupArray,
  27779. workgroupBarrier: workgroupBarrier,
  27780. workgroupId: workgroupId,
  27781. workingToColorSpace: workingToColorSpace,
  27782. xor: xor
  27783. });
  27784. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27785. /**
  27786. * This renderer module manages the background.
  27787. *
  27788. * @private
  27789. * @augments DataMap
  27790. */
  27791. class Background extends DataMap {
  27792. /**
  27793. * Constructs a new background management component.
  27794. *
  27795. * @param {Renderer} renderer - The renderer.
  27796. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27797. */
  27798. constructor( renderer, nodes ) {
  27799. super();
  27800. /**
  27801. * The renderer.
  27802. *
  27803. * @type {Renderer}
  27804. */
  27805. this.renderer = renderer;
  27806. /**
  27807. * Renderer component for managing nodes related logic.
  27808. *
  27809. * @type {Nodes}
  27810. */
  27811. this.nodes = nodes;
  27812. }
  27813. /**
  27814. * Updates the background for the given scene. Depending on how `Scene.background`
  27815. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27816. * or add a mesh to the render list for rendering the background as a textured plane
  27817. * or skybox.
  27818. *
  27819. * @param {Scene} scene - The scene.
  27820. * @param {RenderList} renderList - The current render list.
  27821. * @param {RenderContext} renderContext - The current render context.
  27822. */
  27823. update( scene, renderList, renderContext ) {
  27824. const renderer = this.renderer;
  27825. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27826. let forceClear = false;
  27827. if ( background === null ) {
  27828. // no background settings, use clear color configuration from the renderer
  27829. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27830. _clearColor$1.a = renderer._clearColor.a;
  27831. } else if ( background.isColor === true ) {
  27832. // background is an opaque color
  27833. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27834. _clearColor$1.a = 1;
  27835. forceClear = true;
  27836. } else if ( background.isNode === true ) {
  27837. const sceneData = this.get( scene );
  27838. const backgroundNode = background;
  27839. _clearColor$1.copy( renderer._clearColor );
  27840. let backgroundMesh = sceneData.backgroundMesh;
  27841. if ( backgroundMesh === undefined ) {
  27842. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27843. // @TODO: Add Texture2D support using node context
  27844. getUV: () => backgroundRotation.mul( normalWorld ),
  27845. getTextureLevel: () => backgroundBlurriness
  27846. } );
  27847. let viewProj = modelViewProjection;
  27848. viewProj = viewProj.setZ( viewProj.w );
  27849. const nodeMaterial = new NodeMaterial();
  27850. nodeMaterial.name = 'Background.material';
  27851. nodeMaterial.side = BackSide;
  27852. nodeMaterial.depthTest = false;
  27853. nodeMaterial.depthWrite = false;
  27854. nodeMaterial.fog = false;
  27855. nodeMaterial.lights = false;
  27856. nodeMaterial.vertexNode = viewProj;
  27857. nodeMaterial.colorNode = backgroundMeshNode;
  27858. sceneData.backgroundMeshNode = backgroundMeshNode;
  27859. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27860. backgroundMesh.frustumCulled = false;
  27861. backgroundMesh.name = 'Background.mesh';
  27862. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27863. this.matrixWorld.copyPosition( camera.matrixWorld );
  27864. };
  27865. }
  27866. const backgroundCacheKey = backgroundNode.getCacheKey();
  27867. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27868. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27869. sceneData.backgroundMeshNode.needsUpdate = true;
  27870. backgroundMesh.material.needsUpdate = true;
  27871. sceneData.backgroundCacheKey = backgroundCacheKey;
  27872. }
  27873. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27874. } else {
  27875. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27876. }
  27877. //
  27878. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  27879. if ( environmentBlendMode === 'additive' ) {
  27880. _clearColor$1.set( 0, 0, 0, 1 );
  27881. } else if ( environmentBlendMode === 'alpha-blend' ) {
  27882. _clearColor$1.set( 0, 0, 0, 0 );
  27883. }
  27884. //
  27885. if ( renderer.autoClear === true || forceClear === true ) {
  27886. const clearColorValue = renderContext.clearColorValue;
  27887. clearColorValue.r = _clearColor$1.r;
  27888. clearColorValue.g = _clearColor$1.g;
  27889. clearColorValue.b = _clearColor$1.b;
  27890. clearColorValue.a = _clearColor$1.a;
  27891. // premultiply alpha
  27892. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27893. clearColorValue.r *= clearColorValue.a;
  27894. clearColorValue.g *= clearColorValue.a;
  27895. clearColorValue.b *= clearColorValue.a;
  27896. }
  27897. //
  27898. renderContext.depthClearValue = renderer._clearDepth;
  27899. renderContext.stencilClearValue = renderer._clearStencil;
  27900. renderContext.clearColor = renderer.autoClearColor === true;
  27901. renderContext.clearDepth = renderer.autoClearDepth === true;
  27902. renderContext.clearStencil = renderer.autoClearStencil === true;
  27903. } else {
  27904. renderContext.clearColor = false;
  27905. renderContext.clearDepth = false;
  27906. renderContext.clearStencil = false;
  27907. }
  27908. }
  27909. }
  27910. let _id$6 = 0;
  27911. /**
  27912. * A bind group represents a collection of bindings and thus a collection
  27913. * or resources. Bind groups are assigned to pipelines to provide them
  27914. * with the required resources (like uniform buffers or textures).
  27915. *
  27916. * @private
  27917. */
  27918. class BindGroup {
  27919. /**
  27920. * Constructs a new bind group.
  27921. *
  27922. * @param {String} name - The bind group's name.
  27923. * @param {Array<Binding>} bindings - An array of bindings.
  27924. * @param {Number} index - The group index.
  27925. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27926. */
  27927. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27928. /**
  27929. * The bind group's name.
  27930. *
  27931. * @type {String}
  27932. */
  27933. this.name = name;
  27934. /**
  27935. * An array of bindings.
  27936. *
  27937. * @type {Array<Binding>}
  27938. */
  27939. this.bindings = bindings;
  27940. /**
  27941. * The group index.
  27942. *
  27943. * @type {Number}
  27944. */
  27945. this.index = index;
  27946. /**
  27947. * An array of reference bindings.
  27948. *
  27949. * @type {Array<Binding>}
  27950. */
  27951. this.bindingsReference = bindingsReference;
  27952. /**
  27953. * The group's ID.
  27954. *
  27955. * @type {Number}
  27956. */
  27957. this.id = _id$6 ++;
  27958. }
  27959. }
  27960. /**
  27961. * This module represents the state of a node builder after it was
  27962. * used to build the nodes for a render object. The state holds the
  27963. * results of the build for further processing in the renderer.
  27964. *
  27965. * Render objects with identical cache keys share the same node builder state.
  27966. *
  27967. * @private
  27968. */
  27969. class NodeBuilderState {
  27970. /**
  27971. * Constructs a new node builder state.
  27972. *
  27973. * @param {String?} vertexShader - The native vertex shader code.
  27974. * @param {String?} fragmentShader - The native fragment shader code.
  27975. * @param {String?} computeShader - The native compute shader code.
  27976. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27977. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27978. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27979. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27980. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27981. * @param {NodeMaterialObserver} observer - A node material observer.
  27982. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27983. */
  27984. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  27985. /**
  27986. * The native vertex shader code.
  27987. *
  27988. * @type {String}
  27989. */
  27990. this.vertexShader = vertexShader;
  27991. /**
  27992. * The native fragment shader code.
  27993. *
  27994. * @type {String}
  27995. */
  27996. this.fragmentShader = fragmentShader;
  27997. /**
  27998. * The native compute shader code.
  27999. *
  28000. * @type {String}
  28001. */
  28002. this.computeShader = computeShader;
  28003. /**
  28004. * An array with transform attribute objects.
  28005. * Only relevant when using compute shaders with WebGL 2.
  28006. *
  28007. * @type {Array<Object>}
  28008. */
  28009. this.transforms = transforms;
  28010. /**
  28011. * An array of node attributes representing
  28012. * the attributes of the shaders.
  28013. *
  28014. * @type {Array<NodeAttribute>}
  28015. */
  28016. this.nodeAttributes = nodeAttributes;
  28017. /**
  28018. * An array of bind groups representing the uniform or storage
  28019. * buffers, texture or samplers of the shader.
  28020. *
  28021. * @type {Array<BindGroup>}
  28022. */
  28023. this.bindings = bindings;
  28024. /**
  28025. * An array of nodes that implement their `update()` method.
  28026. *
  28027. * @type {Array<Node>}
  28028. */
  28029. this.updateNodes = updateNodes;
  28030. /**
  28031. * An array of nodes that implement their `updateBefore()` method.
  28032. *
  28033. * @type {Array<Node>}
  28034. */
  28035. this.updateBeforeNodes = updateBeforeNodes;
  28036. /**
  28037. * An array of nodes that implement their `updateAfter()` method.
  28038. *
  28039. * @type {Array<Node>}
  28040. */
  28041. this.updateAfterNodes = updateAfterNodes;
  28042. /**
  28043. * A node material observer.
  28044. *
  28045. * @type {NodeMaterialObserver}
  28046. */
  28047. this.observer = observer;
  28048. /**
  28049. * How often this state is used by render objects.
  28050. *
  28051. * @type {Number}
  28052. */
  28053. this.usedTimes = 0;
  28054. }
  28055. /**
  28056. * This method is used to create a array of bind groups based
  28057. * on the existing bind groups of this state. Shared groups are
  28058. * not cloned.
  28059. *
  28060. * @return {Array<BindGroup>} A array of bind groups.
  28061. */
  28062. createBindings() {
  28063. const bindings = [];
  28064. for ( const instanceGroup of this.bindings ) {
  28065. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28066. if ( shared !== true ) {
  28067. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28068. bindings.push( bindingsGroup );
  28069. for ( const instanceBinding of instanceGroup.bindings ) {
  28070. bindingsGroup.bindings.push( instanceBinding.clone() );
  28071. }
  28072. } else {
  28073. bindings.push( instanceGroup );
  28074. }
  28075. }
  28076. return bindings;
  28077. }
  28078. }
  28079. /**
  28080. * {@link NodeBuilder} is going to create instances of this class during the build process
  28081. * of nodes. They represent the final shader attributes that are going to be generated
  28082. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28083. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28084. */
  28085. class NodeAttribute {
  28086. /**
  28087. * Constructs a new node attribute.
  28088. *
  28089. * @param {String} name - The name of the attribute.
  28090. * @param {String} type - The type of the attribute.
  28091. * @param {Node?} node - An optional reference to the node.
  28092. */
  28093. constructor( name, type, node = null ) {
  28094. /**
  28095. * This flag can be used for type testing.
  28096. *
  28097. * @type {Boolean}
  28098. * @readonly
  28099. * @default true
  28100. */
  28101. this.isNodeAttribute = true;
  28102. /**
  28103. * The name of the attribute.
  28104. *
  28105. * @type {String}
  28106. */
  28107. this.name = name;
  28108. /**
  28109. * The type of the attribute.
  28110. *
  28111. * @type {String}
  28112. */
  28113. this.type = type;
  28114. /**
  28115. * An optional reference to the node.
  28116. *
  28117. * @type {Node?}
  28118. * @default null
  28119. */
  28120. this.node = node;
  28121. }
  28122. }
  28123. /**
  28124. * {@link NodeBuilder} is going to create instances of this class during the build process
  28125. * of nodes. They represent the final shader uniforms that are going to be generated
  28126. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28127. * for this purpose.
  28128. */
  28129. class NodeUniform {
  28130. /**
  28131. * Constructs a new node uniform.
  28132. *
  28133. * @param {String} name - The name of the uniform.
  28134. * @param {String} type - The type of the uniform.
  28135. * @param {UniformNode} node - An reference to the node.
  28136. */
  28137. constructor( name, type, node ) {
  28138. /**
  28139. * This flag can be used for type testing.
  28140. *
  28141. * @type {Boolean}
  28142. * @readonly
  28143. * @default true
  28144. */
  28145. this.isNodeUniform = true;
  28146. /**
  28147. * The name of the uniform.
  28148. *
  28149. * @type {String}
  28150. */
  28151. this.name = name;
  28152. /**
  28153. * The type of the uniform.
  28154. *
  28155. * @type {String}
  28156. */
  28157. this.type = type;
  28158. /**
  28159. * An reference to the node.
  28160. *
  28161. * @type {UniformNode}
  28162. */
  28163. this.node = node.getSelf();
  28164. }
  28165. /**
  28166. * The value of the uniform node.
  28167. *
  28168. * @type {Any}
  28169. */
  28170. get value() {
  28171. return this.node.value;
  28172. }
  28173. set value( val ) {
  28174. this.node.value = val;
  28175. }
  28176. /**
  28177. * The id of the uniform node.
  28178. *
  28179. * @type {Number}
  28180. */
  28181. get id() {
  28182. return this.node.id;
  28183. }
  28184. /**
  28185. * The uniform node's group.
  28186. *
  28187. * @type {UniformGroupNode}
  28188. */
  28189. get groupNode() {
  28190. return this.node.groupNode;
  28191. }
  28192. }
  28193. /**
  28194. * {@link NodeBuilder} is going to create instances of this class during the build process
  28195. * of nodes. They represent the final shader variables that are going to be generated
  28196. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28197. * this purpose.
  28198. */
  28199. class NodeVar {
  28200. /**
  28201. * Constructs a new node variable.
  28202. *
  28203. * @param {String} name - The name of the variable.
  28204. * @param {String} type - The type of the variable.
  28205. * @param {Boolean} [readOnly=false] - The read-only flag.
  28206. */
  28207. constructor( name, type, readOnly = false ) {
  28208. /**
  28209. * This flag can be used for type testing.
  28210. *
  28211. * @type {Boolean}
  28212. * @readonly
  28213. * @default true
  28214. */
  28215. this.isNodeVar = true;
  28216. /**
  28217. * The name of the variable.
  28218. *
  28219. * @type {String}
  28220. */
  28221. this.name = name;
  28222. /**
  28223. * The type of the variable.
  28224. *
  28225. * @type {String}
  28226. */
  28227. this.type = type;
  28228. /**
  28229. * The read-only flag.
  28230. *
  28231. * @type {boolean}
  28232. */
  28233. this.readOnly = readOnly;
  28234. }
  28235. }
  28236. /**
  28237. * {@link NodeBuilder} is going to create instances of this class during the build process
  28238. * of nodes. They represent the final shader varyings that are going to be generated
  28239. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28240. * this purpose.
  28241. *
  28242. * @augments NodeVar
  28243. */
  28244. class NodeVarying extends NodeVar {
  28245. /**
  28246. * Constructs a new node varying.
  28247. *
  28248. * @param {String} name - The name of the varying.
  28249. * @param {String} type - The type of the varying.
  28250. */
  28251. constructor( name, type ) {
  28252. super( name, type );
  28253. /**
  28254. * Whether this varying requires interpolation or not. This property can be used
  28255. * to check if the varying can be optimized for a variable.
  28256. *
  28257. * @type {Boolean}
  28258. * @default false
  28259. */
  28260. this.needsInterpolation = false;
  28261. /**
  28262. * This flag can be used for type testing.
  28263. *
  28264. * @type {Boolean}
  28265. * @readonly
  28266. * @default true
  28267. */
  28268. this.isNodeVarying = true;
  28269. }
  28270. }
  28271. /**
  28272. * {@link NodeBuilder} is going to create instances of this class during the build process
  28273. * of nodes. They represent user-defined, native shader code portions that are going to be
  28274. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28275. * for this purpose.
  28276. */
  28277. class NodeCode {
  28278. /**
  28279. * Constructs a new code node.
  28280. *
  28281. * @param {String} name - The name of the code.
  28282. * @param {String} type - The node type.
  28283. * @param {String} [code=''] - The native shader code.
  28284. */
  28285. constructor( name, type, code = '' ) {
  28286. /**
  28287. * The name of the code.
  28288. *
  28289. * @type {String}
  28290. */
  28291. this.name = name;
  28292. /**
  28293. * The node type.
  28294. *
  28295. * @type {String}
  28296. */
  28297. this.type = type;
  28298. /**
  28299. * The native shader code.
  28300. *
  28301. * @type {String}
  28302. * @default ''
  28303. */
  28304. this.code = code;
  28305. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28306. }
  28307. }
  28308. let _id$5 = 0;
  28309. /**
  28310. * This utility class is used in {@link NodeBuilder} as an internal
  28311. * cache data structure for node data.
  28312. */
  28313. class NodeCache {
  28314. /**
  28315. * Constructs a new node cache.
  28316. *
  28317. * @param {NodeCache?} parent - A reference to a parent cache.
  28318. */
  28319. constructor( parent = null ) {
  28320. /**
  28321. * The id of the cache.
  28322. *
  28323. * @type {Number}
  28324. * @readonly
  28325. */
  28326. this.id = _id$5 ++;
  28327. /**
  28328. * A weak map for managing node data.
  28329. *
  28330. * @type {WeakMap<Node, Object>}
  28331. */
  28332. this.nodesData = new WeakMap();
  28333. /**
  28334. * Reference to a parent node cache.
  28335. *
  28336. * @type {NodeCache?}
  28337. * @default null
  28338. */
  28339. this.parent = parent;
  28340. }
  28341. /**
  28342. * Returns the data for the given node.
  28343. *
  28344. * @param {Node} node - The node.
  28345. * @return {Object?} The data for the node.
  28346. */
  28347. getData( node ) {
  28348. let data = this.nodesData.get( node );
  28349. if ( data === undefined && this.parent !== null ) {
  28350. data = this.parent.getData( node );
  28351. }
  28352. return data;
  28353. }
  28354. /**
  28355. * Sets the data for a given node.
  28356. *
  28357. * @param {Node} node - The node.
  28358. * @param {Object} data - The data that should be cached.
  28359. */
  28360. setData( node, data ) {
  28361. this.nodesData.set( node, data );
  28362. }
  28363. }
  28364. /**
  28365. * {@link NodeBuilder} is going to create instances of this class during the build process
  28366. * of nodes. They represent the final shader struct data that are going to be generated
  28367. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28368. * for this purpose.
  28369. */
  28370. class StructTypeNode extends Node {
  28371. static get type() {
  28372. return 'StructTypeNode';
  28373. }
  28374. /**
  28375. * Constructs a new struct type node.
  28376. *
  28377. * @param {String} name - The name of the struct.
  28378. * @param {Array<String>} types - An array of types.
  28379. */
  28380. constructor( name, types ) {
  28381. super();
  28382. /**
  28383. * The name of the struct.
  28384. *
  28385. * @type {String}
  28386. */
  28387. this.name = name;
  28388. /**
  28389. * An array of types.
  28390. *
  28391. * @type {Array<String>}
  28392. */
  28393. this.types = types;
  28394. /**
  28395. * This flag can be used for type testing.
  28396. *
  28397. * @type {Boolean}
  28398. * @readonly
  28399. * @default true
  28400. */
  28401. this.isStructTypeNode = true;
  28402. }
  28403. /**
  28404. * Returns the member types.
  28405. *
  28406. * @return {Array<String>} The types.
  28407. */
  28408. getMemberTypes() {
  28409. return this.types;
  28410. }
  28411. }
  28412. /**
  28413. * Abstract base class for uniforms.
  28414. *
  28415. * @abstract
  28416. * @private
  28417. */
  28418. class Uniform {
  28419. /**
  28420. * Constructs a new uniform.
  28421. *
  28422. * @param {String} name - The uniform's name.
  28423. * @param {Any} value - The uniform's value.
  28424. */
  28425. constructor( name, value ) {
  28426. /**
  28427. * The uniform's name.
  28428. *
  28429. * @type {String}
  28430. */
  28431. this.name = name;
  28432. /**
  28433. * The uniform's value.
  28434. *
  28435. * @type {Any}
  28436. */
  28437. this.value = value;
  28438. /**
  28439. * Used to build the uniform buffer according to the STD140 layout.
  28440. * Derived uniforms will set this property to a data type specific
  28441. * value.
  28442. *
  28443. * @type {Number}
  28444. */
  28445. this.boundary = 0;
  28446. /**
  28447. * The item size. Derived uniforms will set this property to a data
  28448. * type specific value.
  28449. *
  28450. * @type {Number}
  28451. */
  28452. this.itemSize = 0;
  28453. /**
  28454. * This property is set by {@link UniformsGroup} and marks
  28455. * the start position in the uniform buffer.
  28456. *
  28457. * @type {Number}
  28458. */
  28459. this.offset = 0;
  28460. }
  28461. /**
  28462. * Sets the uniform's value.
  28463. *
  28464. * @param {Any} value - The value to set.
  28465. */
  28466. setValue( value ) {
  28467. this.value = value;
  28468. }
  28469. /**
  28470. * Returns the uniform's value.
  28471. *
  28472. * @return {Any} The value.
  28473. */
  28474. getValue() {
  28475. return this.value;
  28476. }
  28477. }
  28478. /**
  28479. * Represents a Number uniform.
  28480. *
  28481. * @private
  28482. * @augments Uniform
  28483. */
  28484. class NumberUniform extends Uniform {
  28485. /**
  28486. * Constructs a new Number uniform.
  28487. *
  28488. * @param {String} name - The uniform's name.
  28489. * @param {Number} value - The uniform's value.
  28490. */
  28491. constructor( name, value = 0 ) {
  28492. super( name, value );
  28493. /**
  28494. * This flag can be used for type testing.
  28495. *
  28496. * @type {Boolean}
  28497. * @readonly
  28498. * @default true
  28499. */
  28500. this.isNumberUniform = true;
  28501. this.boundary = 4;
  28502. this.itemSize = 1;
  28503. }
  28504. }
  28505. /**
  28506. * Represents a Vector2 uniform.
  28507. *
  28508. * @private
  28509. * @augments Uniform
  28510. */
  28511. class Vector2Uniform extends Uniform {
  28512. /**
  28513. * Constructs a new Number uniform.
  28514. *
  28515. * @param {String} name - The uniform's name.
  28516. * @param {Vector2} value - The uniform's value.
  28517. */
  28518. constructor( name, value = new Vector2() ) {
  28519. super( name, value );
  28520. /**
  28521. * This flag can be used for type testing.
  28522. *
  28523. * @type {Boolean}
  28524. * @readonly
  28525. * @default true
  28526. */
  28527. this.isVector2Uniform = true;
  28528. this.boundary = 8;
  28529. this.itemSize = 2;
  28530. }
  28531. }
  28532. /**
  28533. * Represents a Vector3 uniform.
  28534. *
  28535. * @private
  28536. * @augments Uniform
  28537. */
  28538. class Vector3Uniform extends Uniform {
  28539. /**
  28540. * Constructs a new Number uniform.
  28541. *
  28542. * @param {String} name - The uniform's name.
  28543. * @param {Vector3} value - The uniform's value.
  28544. */
  28545. constructor( name, value = new Vector3() ) {
  28546. super( name, value );
  28547. /**
  28548. * This flag can be used for type testing.
  28549. *
  28550. * @type {Boolean}
  28551. * @readonly
  28552. * @default true
  28553. */
  28554. this.isVector3Uniform = true;
  28555. this.boundary = 16;
  28556. this.itemSize = 3;
  28557. }
  28558. }
  28559. /**
  28560. * Represents a Vector4 uniform.
  28561. *
  28562. * @private
  28563. * @augments Uniform
  28564. */
  28565. class Vector4Uniform extends Uniform {
  28566. /**
  28567. * Constructs a new Number uniform.
  28568. *
  28569. * @param {String} name - The uniform's name.
  28570. * @param {Vector4} value - The uniform's value.
  28571. */
  28572. constructor( name, value = new Vector4() ) {
  28573. super( name, value );
  28574. /**
  28575. * This flag can be used for type testing.
  28576. *
  28577. * @type {Boolean}
  28578. * @readonly
  28579. * @default true
  28580. */
  28581. this.isVector4Uniform = true;
  28582. this.boundary = 16;
  28583. this.itemSize = 4;
  28584. }
  28585. }
  28586. /**
  28587. * Represents a Color uniform.
  28588. *
  28589. * @private
  28590. * @augments Uniform
  28591. */
  28592. class ColorUniform extends Uniform {
  28593. /**
  28594. * Constructs a new Number uniform.
  28595. *
  28596. * @param {String} name - The uniform's name.
  28597. * @param {Color} value - The uniform's value.
  28598. */
  28599. constructor( name, value = new Color() ) {
  28600. super( name, value );
  28601. /**
  28602. * This flag can be used for type testing.
  28603. *
  28604. * @type {Boolean}
  28605. * @readonly
  28606. * @default true
  28607. */
  28608. this.isColorUniform = true;
  28609. this.boundary = 16;
  28610. this.itemSize = 3;
  28611. }
  28612. }
  28613. /**
  28614. * Represents a Matrix3 uniform.
  28615. *
  28616. * @private
  28617. * @augments Uniform
  28618. */
  28619. class Matrix3Uniform extends Uniform {
  28620. /**
  28621. * Constructs a new Number uniform.
  28622. *
  28623. * @param {String} name - The uniform's name.
  28624. * @param {Matrix3} value - The uniform's value.
  28625. */
  28626. constructor( name, value = new Matrix3() ) {
  28627. super( name, value );
  28628. /**
  28629. * This flag can be used for type testing.
  28630. *
  28631. * @type {Boolean}
  28632. * @readonly
  28633. * @default true
  28634. */
  28635. this.isMatrix3Uniform = true;
  28636. this.boundary = 48;
  28637. this.itemSize = 12;
  28638. }
  28639. }
  28640. /**
  28641. * Represents a Matrix4 uniform.
  28642. *
  28643. * @private
  28644. * @augments Uniform
  28645. */
  28646. class Matrix4Uniform extends Uniform {
  28647. /**
  28648. * Constructs a new Number uniform.
  28649. *
  28650. * @param {String} name - The uniform's name.
  28651. * @param {Matrix4} value - The uniform's value.
  28652. */
  28653. constructor( name, value = new Matrix4() ) {
  28654. super( name, value );
  28655. /**
  28656. * This flag can be used for type testing.
  28657. *
  28658. * @type {Boolean}
  28659. * @readonly
  28660. * @default true
  28661. */
  28662. this.isMatrix4Uniform = true;
  28663. this.boundary = 64;
  28664. this.itemSize = 16;
  28665. }
  28666. }
  28667. /**
  28668. * A special form of Number uniform binding type.
  28669. * It's value is managed by a node object.
  28670. *
  28671. * @private
  28672. * @augments NumberUniform
  28673. */
  28674. class NumberNodeUniform extends NumberUniform {
  28675. /**
  28676. * Constructs a new node-based Number uniform.
  28677. *
  28678. * @param {NodeUniform} nodeUniform - The node uniform.
  28679. */
  28680. constructor( nodeUniform ) {
  28681. super( nodeUniform.name, nodeUniform.value );
  28682. /**
  28683. * The node uniform.
  28684. *
  28685. * @type {NodeUniform}
  28686. */
  28687. this.nodeUniform = nodeUniform;
  28688. }
  28689. /**
  28690. * Overwritten to return the value of the node uniform.
  28691. *
  28692. * @return {Number} The value.
  28693. */
  28694. getValue() {
  28695. return this.nodeUniform.value;
  28696. }
  28697. /**
  28698. * Returns the node uniform data type.
  28699. *
  28700. * @return {String} The data type.
  28701. */
  28702. getType() {
  28703. return this.nodeUniform.type;
  28704. }
  28705. }
  28706. /**
  28707. * A special form of Vector2 uniform binding type.
  28708. * It's value is managed by a node object.
  28709. *
  28710. * @private
  28711. * @augments Vector2Uniform
  28712. */
  28713. class Vector2NodeUniform extends Vector2Uniform {
  28714. /**
  28715. * Constructs a new node-based Vector2 uniform.
  28716. *
  28717. * @param {NodeUniform} nodeUniform - The node uniform.
  28718. */
  28719. constructor( nodeUniform ) {
  28720. super( nodeUniform.name, nodeUniform.value );
  28721. /**
  28722. * The node uniform.
  28723. *
  28724. * @type {NodeUniform}
  28725. */
  28726. this.nodeUniform = nodeUniform;
  28727. }
  28728. /**
  28729. * Overwritten to return the value of the node uniform.
  28730. *
  28731. * @return {Vector2} The value.
  28732. */
  28733. getValue() {
  28734. return this.nodeUniform.value;
  28735. }
  28736. /**
  28737. * Returns the node uniform data type.
  28738. *
  28739. * @return {String} The data type.
  28740. */
  28741. getType() {
  28742. return this.nodeUniform.type;
  28743. }
  28744. }
  28745. /**
  28746. * A special form of Vector3 uniform binding type.
  28747. * It's value is managed by a node object.
  28748. *
  28749. * @private
  28750. * @augments Vector3Uniform
  28751. */
  28752. class Vector3NodeUniform extends Vector3Uniform {
  28753. /**
  28754. * Constructs a new node-based Vector3 uniform.
  28755. *
  28756. * @param {NodeUniform} nodeUniform - The node uniform.
  28757. */
  28758. constructor( nodeUniform ) {
  28759. super( nodeUniform.name, nodeUniform.value );
  28760. /**
  28761. * The node uniform.
  28762. *
  28763. * @type {NodeUniform}
  28764. */
  28765. this.nodeUniform = nodeUniform;
  28766. }
  28767. /**
  28768. * Overwritten to return the value of the node uniform.
  28769. *
  28770. * @return {Vector3} The value.
  28771. */
  28772. getValue() {
  28773. return this.nodeUniform.value;
  28774. }
  28775. /**
  28776. * Returns the node uniform data type.
  28777. *
  28778. * @return {String} The data type.
  28779. */
  28780. getType() {
  28781. return this.nodeUniform.type;
  28782. }
  28783. }
  28784. /**
  28785. * A special form of Vector4 uniform binding type.
  28786. * It's value is managed by a node object.
  28787. *
  28788. * @private
  28789. * @augments Vector4Uniform
  28790. */
  28791. class Vector4NodeUniform extends Vector4Uniform {
  28792. /**
  28793. * Constructs a new node-based Vector4 uniform.
  28794. *
  28795. * @param {NodeUniform} nodeUniform - The node uniform.
  28796. */
  28797. constructor( nodeUniform ) {
  28798. super( nodeUniform.name, nodeUniform.value );
  28799. /**
  28800. * The node uniform.
  28801. *
  28802. * @type {NodeUniform}
  28803. */
  28804. this.nodeUniform = nodeUniform;
  28805. }
  28806. /**
  28807. * Overwritten to return the value of the node uniform.
  28808. *
  28809. * @return {Vector4} The value.
  28810. */
  28811. getValue() {
  28812. return this.nodeUniform.value;
  28813. }
  28814. /**
  28815. * Returns the node uniform data type.
  28816. *
  28817. * @return {String} The data type.
  28818. */
  28819. getType() {
  28820. return this.nodeUniform.type;
  28821. }
  28822. }
  28823. /**
  28824. * A special form of Color uniform binding type.
  28825. * It's value is managed by a node object.
  28826. *
  28827. * @private
  28828. * @augments ColorUniform
  28829. */
  28830. class ColorNodeUniform extends ColorUniform {
  28831. /**
  28832. * Constructs a new node-based Color uniform.
  28833. *
  28834. * @param {NodeUniform} nodeUniform - The node uniform.
  28835. */
  28836. constructor( nodeUniform ) {
  28837. super( nodeUniform.name, nodeUniform.value );
  28838. /**
  28839. * The node uniform.
  28840. *
  28841. * @type {NodeUniform}
  28842. */
  28843. this.nodeUniform = nodeUniform;
  28844. }
  28845. /**
  28846. * Overwritten to return the value of the node uniform.
  28847. *
  28848. * @return {Color} The value.
  28849. */
  28850. getValue() {
  28851. return this.nodeUniform.value;
  28852. }
  28853. /**
  28854. * Returns the node uniform data type.
  28855. *
  28856. * @return {String} The data type.
  28857. */
  28858. getType() {
  28859. return this.nodeUniform.type;
  28860. }
  28861. }
  28862. /**
  28863. * A special form of Matrix3 uniform binding type.
  28864. * It's value is managed by a node object.
  28865. *
  28866. * @private
  28867. * @augments Matrix3Uniform
  28868. */
  28869. class Matrix3NodeUniform extends Matrix3Uniform {
  28870. /**
  28871. * Constructs a new node-based Matrix3 uniform.
  28872. *
  28873. * @param {NodeUniform} nodeUniform - The node uniform.
  28874. */
  28875. constructor( nodeUniform ) {
  28876. super( nodeUniform.name, nodeUniform.value );
  28877. /**
  28878. * The node uniform.
  28879. *
  28880. * @type {NodeUniform}
  28881. */
  28882. this.nodeUniform = nodeUniform;
  28883. }
  28884. /**
  28885. * Overwritten to return the value of the node uniform.
  28886. *
  28887. * @return {Matrix3} The value.
  28888. */
  28889. getValue() {
  28890. return this.nodeUniform.value;
  28891. }
  28892. /**
  28893. * Returns the node uniform data type.
  28894. *
  28895. * @return {String} The data type.
  28896. */
  28897. getType() {
  28898. return this.nodeUniform.type;
  28899. }
  28900. }
  28901. /**
  28902. * A special form of Matrix4 uniform binding type.
  28903. * It's value is managed by a node object.
  28904. *
  28905. * @private
  28906. * @augments Matrix4Uniform
  28907. */
  28908. class Matrix4NodeUniform extends Matrix4Uniform {
  28909. /**
  28910. * Constructs a new node-based Matrix4 uniform.
  28911. *
  28912. * @param {NodeUniform} nodeUniform - The node uniform.
  28913. */
  28914. constructor( nodeUniform ) {
  28915. super( nodeUniform.name, nodeUniform.value );
  28916. /**
  28917. * The node uniform.
  28918. *
  28919. * @type {NodeUniform}
  28920. */
  28921. this.nodeUniform = nodeUniform;
  28922. }
  28923. /**
  28924. * Overwritten to return the value of the node uniform.
  28925. *
  28926. * @return {Matrix4} The value.
  28927. */
  28928. getValue() {
  28929. return this.nodeUniform.value;
  28930. }
  28931. /**
  28932. * Returns the node uniform data type.
  28933. *
  28934. * @return {String} The data type.
  28935. */
  28936. getType() {
  28937. return this.nodeUniform.type;
  28938. }
  28939. }
  28940. const LOD_MIN = 4;
  28941. // The standard deviations (radians) associated with the extra mips. These are
  28942. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28943. // geometric shadowing function. These sigma values squared must match the
  28944. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28945. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28946. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28947. // samples and exit early, but not recompile the shader.
  28948. const MAX_SAMPLES = 20;
  28949. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28950. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28951. const _clearColor = /*@__PURE__*/ new Color();
  28952. let _oldTarget = null;
  28953. let _oldActiveCubeFace = 0;
  28954. let _oldActiveMipmapLevel = 0;
  28955. // Golden Ratio
  28956. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28957. const INV_PHI = 1 / PHI;
  28958. // Vertices of a dodecahedron (except the opposites, which represent the
  28959. // same axis), used as axis directions evenly spread on a sphere.
  28960. const _axisDirections = [
  28961. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28962. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28963. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28964. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28965. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28966. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28967. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28968. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28969. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28970. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28971. ];
  28972. // maps blur materials to their uniforms dictionary
  28973. const _uniformsMap = new WeakMap();
  28974. // WebGPU Face indices
  28975. const _faceLib = [
  28976. 3, 1, 5,
  28977. 0, 4, 2
  28978. ];
  28979. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28980. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  28981. /**
  28982. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28983. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28984. * blur to be quickly accessed based on material roughness. It is packed into a
  28985. * special CubeUV format that allows us to perform custom interpolation so that
  28986. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28987. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28988. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28989. * higher roughness levels. In this way we maintain resolution to smoothly
  28990. * interpolate diffuse lighting while limiting sampling computation.
  28991. *
  28992. * Paper: Fast, Accurate Image-Based Lighting
  28993. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28994. */
  28995. class PMREMGenerator {
  28996. constructor( renderer ) {
  28997. this._renderer = renderer;
  28998. this._pingPongRenderTarget = null;
  28999. this._lodMax = 0;
  29000. this._cubeSize = 0;
  29001. this._lodPlanes = [];
  29002. this._sizeLods = [];
  29003. this._sigmas = [];
  29004. this._lodMeshes = [];
  29005. this._blurMaterial = null;
  29006. this._cubemapMaterial = null;
  29007. this._equirectMaterial = null;
  29008. this._backgroundBox = null;
  29009. }
  29010. get _hasInitialized() {
  29011. return this._renderer.hasInitialized();
  29012. }
  29013. /**
  29014. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29015. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29016. * in radians to be applied to the scene before PMREM generation. Optional near
  29017. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29018. * is placed at the origin).
  29019. *
  29020. * @param {Scene} scene - The scene to be captured.
  29021. * @param {Number} [sigma=0] - The blur radius in radians.
  29022. * @param {Number} [near=0.1] - The near plane distance.
  29023. * @param {Number} [far=100] - The far plane distance.
  29024. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29025. * @return {RenderTarget} The resulting PMREM.
  29026. * @see fromSceneAsync
  29027. */
  29028. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29029. this._setSize( 256 );
  29030. if ( this._hasInitialized === false ) {
  29031. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29032. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29033. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29034. return cubeUVRenderTarget;
  29035. }
  29036. _oldTarget = this._renderer.getRenderTarget();
  29037. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29038. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29039. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29040. cubeUVRenderTarget.depthBuffer = true;
  29041. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29042. if ( sigma > 0 ) {
  29043. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29044. }
  29045. this._applyPMREM( cubeUVRenderTarget );
  29046. this._cleanup( cubeUVRenderTarget );
  29047. return cubeUVRenderTarget;
  29048. }
  29049. /**
  29050. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29051. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29052. * in radians to be applied to the scene before PMREM generation. Optional near
  29053. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29054. * is placed at the origin).
  29055. *
  29056. * @param {Scene} scene - The scene to be captured.
  29057. * @param {Number} [sigma=0] - The blur radius in radians.
  29058. * @param {Number} [near=0.1] - The near plane distance.
  29059. * @param {Number} [far=100] - The far plane distance.
  29060. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29061. * @return {Promise<RenderTarget>} The resulting PMREM.
  29062. * @see fromScene
  29063. */
  29064. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29065. if ( this._hasInitialized === false ) await this._renderer.init();
  29066. return this.fromScene( scene, sigma, near, far, renderTarget );
  29067. }
  29068. /**
  29069. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29070. * or HDR. The ideal input image size is 1k (1024 x 512),
  29071. * as this matches best with the 256 x 256 cubemap output.
  29072. *
  29073. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29074. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29075. * @return {RenderTarget} The resulting PMREM.
  29076. * @see fromEquirectangularAsync
  29077. */
  29078. fromEquirectangular( equirectangular, renderTarget = null ) {
  29079. if ( this._hasInitialized === false ) {
  29080. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29081. this._setSizeFromTexture( equirectangular );
  29082. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29083. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29084. return cubeUVRenderTarget;
  29085. }
  29086. return this._fromTexture( equirectangular, renderTarget );
  29087. }
  29088. /**
  29089. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29090. * or HDR. The ideal input image size is 1k (1024 x 512),
  29091. * as this matches best with the 256 x 256 cubemap output.
  29092. *
  29093. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29094. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29095. * @return {Promise<RenderTarget>} The resulting PMREM.
  29096. * @see fromEquirectangular
  29097. */
  29098. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29099. if ( this._hasInitialized === false ) await this._renderer.init();
  29100. return this._fromTexture( equirectangular, renderTarget );
  29101. }
  29102. /**
  29103. * Generates a PMREM from an cubemap texture, which can be either LDR
  29104. * or HDR. The ideal input cube size is 256 x 256,
  29105. * as this matches best with the 256 x 256 cubemap output.
  29106. *
  29107. * @param {Texture} cubemap - The cubemap texture to be converted.
  29108. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29109. * @return {RenderTarget} The resulting PMREM.
  29110. * @see fromCubemapAsync
  29111. */
  29112. fromCubemap( cubemap, renderTarget = null ) {
  29113. if ( this._hasInitialized === false ) {
  29114. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29115. this._setSizeFromTexture( cubemap );
  29116. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29117. this.fromCubemapAsync( cubemap, renderTarget );
  29118. return cubeUVRenderTarget;
  29119. }
  29120. return this._fromTexture( cubemap, renderTarget );
  29121. }
  29122. /**
  29123. * Generates a PMREM from an cubemap texture, which can be either LDR
  29124. * or HDR. The ideal input cube size is 256 x 256,
  29125. * with the 256 x 256 cubemap output.
  29126. *
  29127. * @param {Texture} cubemap - The cubemap texture to be converted.
  29128. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29129. * @return {Promise<RenderTarget>} The resulting PMREM.
  29130. * @see fromCubemap
  29131. */
  29132. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29133. if ( this._hasInitialized === false ) await this._renderer.init();
  29134. return this._fromTexture( cubemap, renderTarget );
  29135. }
  29136. /**
  29137. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29138. * your texture's network fetch for increased concurrency.
  29139. *
  29140. * @returns {Promise}
  29141. */
  29142. async compileCubemapShader() {
  29143. if ( this._cubemapMaterial === null ) {
  29144. this._cubemapMaterial = _getCubemapMaterial();
  29145. await this._compileMaterial( this._cubemapMaterial );
  29146. }
  29147. }
  29148. /**
  29149. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29150. * your texture's network fetch for increased concurrency.
  29151. *
  29152. * @returns {Promise}
  29153. */
  29154. async compileEquirectangularShader() {
  29155. if ( this._equirectMaterial === null ) {
  29156. this._equirectMaterial = _getEquirectMaterial();
  29157. await this._compileMaterial( this._equirectMaterial );
  29158. }
  29159. }
  29160. /**
  29161. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29162. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29163. * one of them will cause any others to also become unusable.
  29164. */
  29165. dispose() {
  29166. this._dispose();
  29167. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29168. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29169. if ( this._backgroundBox !== null ) {
  29170. this._backgroundBox.geometry.dispose();
  29171. this._backgroundBox.material.dispose();
  29172. }
  29173. }
  29174. // private interface
  29175. _setSizeFromTexture( texture ) {
  29176. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29177. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29178. } else { // Equirectangular
  29179. this._setSize( texture.image.width / 4 );
  29180. }
  29181. }
  29182. _setSize( cubeSize ) {
  29183. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29184. this._cubeSize = Math.pow( 2, this._lodMax );
  29185. }
  29186. _dispose() {
  29187. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29188. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29189. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29190. this._lodPlanes[ i ].dispose();
  29191. }
  29192. }
  29193. _cleanup( outputTarget ) {
  29194. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29195. outputTarget.scissorTest = false;
  29196. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29197. }
  29198. _fromTexture( texture, renderTarget ) {
  29199. this._setSizeFromTexture( texture );
  29200. _oldTarget = this._renderer.getRenderTarget();
  29201. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29202. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29203. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29204. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29205. this._applyPMREM( cubeUVRenderTarget );
  29206. this._cleanup( cubeUVRenderTarget );
  29207. return cubeUVRenderTarget;
  29208. }
  29209. _allocateTargets() {
  29210. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29211. const height = 4 * this._cubeSize;
  29212. const params = {
  29213. magFilter: LinearFilter,
  29214. minFilter: LinearFilter,
  29215. generateMipmaps: false,
  29216. type: HalfFloatType,
  29217. format: RGBAFormat,
  29218. colorSpace: LinearSRGBColorSpace,
  29219. //depthBuffer: false
  29220. };
  29221. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29222. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29223. if ( this._pingPongRenderTarget !== null ) {
  29224. this._dispose();
  29225. }
  29226. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29227. const { _lodMax } = this;
  29228. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29229. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29230. }
  29231. return cubeUVRenderTarget;
  29232. }
  29233. async _compileMaterial( material ) {
  29234. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29235. await this._renderer.compile( tmpMesh, _flatCamera );
  29236. }
  29237. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29238. const cubeCamera = _cubeCamera;
  29239. cubeCamera.near = near;
  29240. cubeCamera.far = far;
  29241. // px, py, pz, nx, ny, nz
  29242. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  29243. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  29244. const renderer = this._renderer;
  29245. const originalAutoClear = renderer.autoClear;
  29246. renderer.getClearColor( _clearColor );
  29247. renderer.autoClear = false;
  29248. let backgroundBox = this._backgroundBox;
  29249. if ( backgroundBox === null ) {
  29250. const backgroundMaterial = new MeshBasicMaterial( {
  29251. name: 'PMREM.Background',
  29252. side: BackSide,
  29253. depthWrite: false,
  29254. depthTest: false
  29255. } );
  29256. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29257. }
  29258. let useSolidColor = false;
  29259. const background = scene.background;
  29260. if ( background ) {
  29261. if ( background.isColor ) {
  29262. backgroundBox.material.color.copy( background );
  29263. scene.background = null;
  29264. useSolidColor = true;
  29265. }
  29266. } else {
  29267. backgroundBox.material.color.copy( _clearColor );
  29268. useSolidColor = true;
  29269. }
  29270. renderer.setRenderTarget( cubeUVRenderTarget );
  29271. renderer.clear();
  29272. if ( useSolidColor ) {
  29273. renderer.render( backgroundBox, cubeCamera );
  29274. }
  29275. for ( let i = 0; i < 6; i ++ ) {
  29276. const col = i % 3;
  29277. if ( col === 0 ) {
  29278. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29279. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29280. } else if ( col === 1 ) {
  29281. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29282. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29283. } else {
  29284. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29285. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29286. }
  29287. const size = this._cubeSize;
  29288. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29289. renderer.render( scene, cubeCamera );
  29290. }
  29291. renderer.autoClear = originalAutoClear;
  29292. scene.background = background;
  29293. }
  29294. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29295. const renderer = this._renderer;
  29296. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29297. if ( isCubeTexture ) {
  29298. if ( this._cubemapMaterial === null ) {
  29299. this._cubemapMaterial = _getCubemapMaterial( texture );
  29300. }
  29301. } else {
  29302. if ( this._equirectMaterial === null ) {
  29303. this._equirectMaterial = _getEquirectMaterial( texture );
  29304. }
  29305. }
  29306. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29307. material.fragmentNode.value = texture;
  29308. const mesh = this._lodMeshes[ 0 ];
  29309. mesh.material = material;
  29310. const size = this._cubeSize;
  29311. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29312. renderer.setRenderTarget( cubeUVRenderTarget );
  29313. renderer.render( mesh, _flatCamera );
  29314. }
  29315. _applyPMREM( cubeUVRenderTarget ) {
  29316. const renderer = this._renderer;
  29317. const autoClear = renderer.autoClear;
  29318. renderer.autoClear = false;
  29319. const n = this._lodPlanes.length;
  29320. for ( let i = 1; i < n; i ++ ) {
  29321. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29322. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29323. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29324. }
  29325. renderer.autoClear = autoClear;
  29326. }
  29327. /**
  29328. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29329. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29330. * the blur latitudinally (around the poles), and then longitudinally (towards
  29331. * the poles) to approximate the orthogonally-separable blur. It is least
  29332. * accurate at the poles, but still does a decent job.
  29333. *
  29334. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29335. * @param {Number} lodIn - The input level-of-detail.
  29336. * @param {Number} lodOut - The output level-of-detail.
  29337. * @param {Number} sigma - The blur radius in radians.
  29338. * @param {Vector3} [poleAxis] - The pole axis.
  29339. */
  29340. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29341. const pingPongRenderTarget = this._pingPongRenderTarget;
  29342. this._halfBlur(
  29343. cubeUVRenderTarget,
  29344. pingPongRenderTarget,
  29345. lodIn,
  29346. lodOut,
  29347. sigma,
  29348. 'latitudinal',
  29349. poleAxis );
  29350. this._halfBlur(
  29351. pingPongRenderTarget,
  29352. cubeUVRenderTarget,
  29353. lodOut,
  29354. lodOut,
  29355. sigma,
  29356. 'longitudinal',
  29357. poleAxis );
  29358. }
  29359. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29360. const renderer = this._renderer;
  29361. const blurMaterial = this._blurMaterial;
  29362. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29363. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29364. }
  29365. // Number of standard deviations at which to cut off the discrete approximation.
  29366. const STANDARD_DEVIATIONS = 3;
  29367. const blurMesh = this._lodMeshes[ lodOut ];
  29368. blurMesh.material = blurMaterial;
  29369. const blurUniforms = _uniformsMap.get( blurMaterial );
  29370. const pixels = this._sizeLods[ lodIn ] - 1;
  29371. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29372. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29373. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29374. if ( samples > MAX_SAMPLES ) {
  29375. console.warn( `sigmaRadians, ${
  29376. sigmaRadians}, is too large and will clip, as it requested ${
  29377. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29378. }
  29379. const weights = [];
  29380. let sum = 0;
  29381. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29382. const x = i / sigmaPixels;
  29383. const weight = Math.exp( - x * x / 2 );
  29384. weights.push( weight );
  29385. if ( i === 0 ) {
  29386. sum += weight;
  29387. } else if ( i < samples ) {
  29388. sum += 2 * weight;
  29389. }
  29390. }
  29391. for ( let i = 0; i < weights.length; i ++ ) {
  29392. weights[ i ] = weights[ i ] / sum;
  29393. }
  29394. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29395. blurUniforms.envMap.value = targetIn.texture;
  29396. blurUniforms.samples.value = samples;
  29397. blurUniforms.weights.array = weights;
  29398. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29399. if ( poleAxis ) {
  29400. blurUniforms.poleAxis.value = poleAxis;
  29401. }
  29402. const { _lodMax } = this;
  29403. blurUniforms.dTheta.value = radiansPerPixel;
  29404. blurUniforms.mipInt.value = _lodMax - lodIn;
  29405. const outputSize = this._sizeLods[ lodOut ];
  29406. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29407. const y = 4 * ( this._cubeSize - outputSize );
  29408. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29409. renderer.setRenderTarget( targetOut );
  29410. renderer.render( blurMesh, _flatCamera );
  29411. }
  29412. }
  29413. function _createPlanes( lodMax ) {
  29414. const lodPlanes = [];
  29415. const sizeLods = [];
  29416. const sigmas = [];
  29417. const lodMeshes = [];
  29418. let lod = lodMax;
  29419. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29420. for ( let i = 0; i < totalLods; i ++ ) {
  29421. const sizeLod = Math.pow( 2, lod );
  29422. sizeLods.push( sizeLod );
  29423. let sigma = 1.0 / sizeLod;
  29424. if ( i > lodMax - LOD_MIN ) {
  29425. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29426. } else if ( i === 0 ) {
  29427. sigma = 0;
  29428. }
  29429. sigmas.push( sigma );
  29430. const texelSize = 1.0 / ( sizeLod - 2 );
  29431. const min = - texelSize;
  29432. const max = 1 + texelSize;
  29433. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29434. const cubeFaces = 6;
  29435. const vertices = 6;
  29436. const positionSize = 3;
  29437. const uvSize = 2;
  29438. const faceIndexSize = 1;
  29439. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29440. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29441. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29442. for ( let face = 0; face < cubeFaces; face ++ ) {
  29443. const x = ( face % 3 ) * 2 / 3 - 1;
  29444. const y = face > 2 ? 0 : - 1;
  29445. const coordinates = [
  29446. x, y, 0,
  29447. x + 2 / 3, y, 0,
  29448. x + 2 / 3, y + 1, 0,
  29449. x, y, 0,
  29450. x + 2 / 3, y + 1, 0,
  29451. x, y + 1, 0
  29452. ];
  29453. const faceIdx = _faceLib[ face ];
  29454. position.set( coordinates, positionSize * vertices * faceIdx );
  29455. uv.set( uv1, uvSize * vertices * faceIdx );
  29456. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29457. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29458. }
  29459. const planes = new BufferGeometry();
  29460. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29461. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29462. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29463. lodPlanes.push( planes );
  29464. lodMeshes.push( new Mesh( planes, null ) );
  29465. if ( lod > LOD_MIN ) {
  29466. lod --;
  29467. }
  29468. }
  29469. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29470. }
  29471. function _createRenderTarget( width, height, params ) {
  29472. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29473. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29474. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29475. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29476. cubeUVRenderTarget.scissorTest = true;
  29477. return cubeUVRenderTarget;
  29478. }
  29479. function _setViewport( target, x, y, width, height ) {
  29480. target.viewport.set( x, y, width, height );
  29481. target.scissor.set( x, y, width, height );
  29482. }
  29483. function _getMaterial( type ) {
  29484. const material = new NodeMaterial();
  29485. material.depthTest = false;
  29486. material.depthWrite = false;
  29487. material.blending = NoBlending;
  29488. material.name = `PMREM_${ type }`;
  29489. return material;
  29490. }
  29491. function _getBlurShader( lodMax, width, height ) {
  29492. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29493. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29494. const dTheta = uniform( 0 );
  29495. const n = float( MAX_SAMPLES );
  29496. const latitudinal = uniform( 0 ); // false, bool
  29497. const samples = uniform( 1 ); // int
  29498. const envMap = texture( null );
  29499. const mipInt = uniform( 0 ); // int
  29500. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29501. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29502. const CUBEUV_MAX_MIP = float( lodMax );
  29503. const materialUniforms = {
  29504. n,
  29505. latitudinal,
  29506. weights,
  29507. poleAxis,
  29508. outputDirection: _outputDirection,
  29509. dTheta,
  29510. samples,
  29511. envMap,
  29512. mipInt,
  29513. CUBEUV_TEXEL_WIDTH,
  29514. CUBEUV_TEXEL_HEIGHT,
  29515. CUBEUV_MAX_MIP
  29516. };
  29517. const material = _getMaterial( 'blur' );
  29518. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29519. _uniformsMap.set( material, materialUniforms );
  29520. return material;
  29521. }
  29522. function _getCubemapMaterial( envTexture ) {
  29523. const material = _getMaterial( 'cubemap' );
  29524. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29525. return material;
  29526. }
  29527. function _getEquirectMaterial( envTexture ) {
  29528. const material = _getMaterial( 'equirect' );
  29529. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29530. return material;
  29531. }
  29532. const rendererCache = new WeakMap();
  29533. const typeFromArray = new Map( [
  29534. [ Int8Array, 'int' ],
  29535. [ Int16Array, 'int' ],
  29536. [ Int32Array, 'int' ],
  29537. [ Uint8Array, 'uint' ],
  29538. [ Uint16Array, 'uint' ],
  29539. [ Uint32Array, 'uint' ],
  29540. [ Float32Array, 'float' ]
  29541. ] );
  29542. const toFloat = ( value ) => {
  29543. if ( /e/g.test( value ) ) {
  29544. return String( value ).replace( /\+/g, '' );
  29545. } else {
  29546. value = Number( value );
  29547. return value + ( value % 1 ? '' : '.0' );
  29548. }
  29549. };
  29550. /**
  29551. * Base class for builders which generate a shader program based
  29552. * on a 3D object and its node material definition.
  29553. */
  29554. class NodeBuilder {
  29555. /**
  29556. * Constructs a new node builder.
  29557. *
  29558. * @param {Object3D} object - The 3D object.
  29559. * @param {Renderer} renderer - The current renderer.
  29560. * @param {NodeParser} parser - A reference to a node parser.
  29561. */
  29562. constructor( object, renderer, parser ) {
  29563. /**
  29564. * The 3D object.
  29565. *
  29566. * @type {Object3D}
  29567. */
  29568. this.object = object;
  29569. /**
  29570. * The material of the 3D object.
  29571. *
  29572. * @type {Material?}
  29573. */
  29574. this.material = ( object && object.material ) || null;
  29575. /**
  29576. * The geometry of the 3D object.
  29577. *
  29578. * @type {BufferGeometry?}
  29579. */
  29580. this.geometry = ( object && object.geometry ) || null;
  29581. /**
  29582. * The current renderer.
  29583. *
  29584. * @type {Renderer}
  29585. */
  29586. this.renderer = renderer;
  29587. /**
  29588. * A reference to a node parser.
  29589. *
  29590. * @type {NodeParser}
  29591. */
  29592. this.parser = parser;
  29593. /**
  29594. * The scene the 3D object belongs to.
  29595. *
  29596. * @type {Scene?}
  29597. * @default null
  29598. */
  29599. this.scene = null;
  29600. /**
  29601. * The camera the 3D object is rendered with.
  29602. *
  29603. * @type {Camera?}
  29604. * @default null
  29605. */
  29606. this.camera = null;
  29607. /**
  29608. * A list of all nodes the builder is processing
  29609. * for this 3D object.
  29610. *
  29611. * @type {Array<Node>}
  29612. */
  29613. this.nodes = [];
  29614. /**
  29615. * A list of all sequential nodes.
  29616. *
  29617. * @type {Array<Node>}
  29618. */
  29619. this.sequentialNodes = [];
  29620. /**
  29621. * A list of all nodes which {@link Node#update} method should be executed.
  29622. *
  29623. * @type {Array<Node>}
  29624. */
  29625. this.updateNodes = [];
  29626. /**
  29627. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29628. *
  29629. * @type {Array<Node>}
  29630. */
  29631. this.updateBeforeNodes = [];
  29632. /**
  29633. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29634. *
  29635. * @type {Array<Node>}
  29636. */
  29637. this.updateAfterNodes = [];
  29638. /**
  29639. * A dictionary that assigns each node to a unique hash.
  29640. *
  29641. * @type {Object<Number,Node>}
  29642. */
  29643. this.hashNodes = {};
  29644. /**
  29645. * A reference to a node material observer.
  29646. *
  29647. * @type {NodeMaterialObserver?}
  29648. * @default null
  29649. */
  29650. this.observer = null;
  29651. /**
  29652. * A reference to the current lights node.
  29653. *
  29654. * @type {LightsNode?}
  29655. * @default null
  29656. */
  29657. this.lightsNode = null;
  29658. /**
  29659. * A reference to the current environment node.
  29660. *
  29661. * @type {Node?}
  29662. * @default null
  29663. */
  29664. this.environmentNode = null;
  29665. /**
  29666. * A reference to the current fog node.
  29667. *
  29668. * @type {FogNode?}
  29669. * @default null
  29670. */
  29671. this.fogNode = null;
  29672. /**
  29673. * The current clipping context.
  29674. *
  29675. * @type {ClippingContext?}
  29676. */
  29677. this.clippingContext = null;
  29678. /**
  29679. * The generated vertex shader.
  29680. *
  29681. * @type {String?}
  29682. */
  29683. this.vertexShader = null;
  29684. /**
  29685. * The generated fragment shader.
  29686. *
  29687. * @type {String?}
  29688. */
  29689. this.fragmentShader = null;
  29690. /**
  29691. * The generated compute shader.
  29692. *
  29693. * @type {String?}
  29694. */
  29695. this.computeShader = null;
  29696. /**
  29697. * Nodes used in the primary flow of code generation.
  29698. *
  29699. * @type {Object<String,Array<Node>>}
  29700. */
  29701. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29702. /**
  29703. * Nodes code from `.flowNodes`.
  29704. *
  29705. * @type {Object<String,String>}
  29706. */
  29707. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29708. /**
  29709. * This dictionary holds the node uniforms of the builder.
  29710. * The uniforms are maintained in an array for each shader stage.
  29711. *
  29712. * @type {Object}
  29713. */
  29714. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29715. /**
  29716. * This dictionary holds the output structs of the builder.
  29717. * The structs are maintained in an array for each shader stage.
  29718. *
  29719. * @type {Object}
  29720. */
  29721. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29722. /**
  29723. * This dictionary holds the bindings for each shader stage.
  29724. *
  29725. * @type {Object}
  29726. */
  29727. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29728. /**
  29729. * This dictionary maintains the binding indices per bind group.
  29730. *
  29731. * @type {Object}
  29732. */
  29733. this.bindingsIndexes = {};
  29734. /**
  29735. * Reference to the array of bind groups.
  29736. *
  29737. * @type {Array<BindGroup>?}
  29738. */
  29739. this.bindGroups = null;
  29740. /**
  29741. * This array holds the node attributes of this builder
  29742. * created via {@link AttributeNode}.
  29743. *
  29744. * @type {Array<NodeAttribute>}
  29745. */
  29746. this.attributes = [];
  29747. /**
  29748. * This array holds the node attributes of this builder
  29749. * created via {@link BufferAttributeNode}.
  29750. *
  29751. * @type {Array<NodeAttribute>}
  29752. */
  29753. this.bufferAttributes = [];
  29754. /**
  29755. * This array holds the node varyings of this builder.
  29756. *
  29757. * @type {Array<NodeVarying>}
  29758. */
  29759. this.varyings = [];
  29760. /**
  29761. * This dictionary holds the (native) node codes of this builder.
  29762. * The codes are maintained in an array for each shader stage.
  29763. *
  29764. * @type {Object<String,Array<NodeCode>>}
  29765. */
  29766. this.codes = {};
  29767. /**
  29768. * This dictionary holds the node variables of this builder.
  29769. * The variables are maintained in an array for each shader stage.
  29770. *
  29771. * @type {Object<String,Array<NodeVar>>}
  29772. */
  29773. this.vars = {};
  29774. /**
  29775. * Current code flow.
  29776. * All code generated in this stack will be stored in `.flow`.
  29777. *
  29778. * @type {{code: String}}
  29779. */
  29780. this.flow = { code: '' };
  29781. /**
  29782. * A chain of nodes.
  29783. * Used to check recursive calls in node-graph.
  29784. *
  29785. * @type {Array<Node>}
  29786. */
  29787. this.chaining = [];
  29788. /**
  29789. * The current stack.
  29790. * This reflects the current process in the code block hierarchy,
  29791. * it is useful to know if the current process is inside a conditional for example.
  29792. *
  29793. * @type {StackNode}
  29794. */
  29795. this.stack = stack();
  29796. /**
  29797. * List of stack nodes.
  29798. * The current stack hierarchy is stored in an array.
  29799. *
  29800. * @type {Array<StackNode>}
  29801. */
  29802. this.stacks = [];
  29803. /**
  29804. * A tab value. Used for shader string generation.
  29805. *
  29806. * @type {String}
  29807. * @default '\t'
  29808. */
  29809. this.tab = '\t';
  29810. /**
  29811. * Reference to the current function node.
  29812. *
  29813. * @type {FunctionNode?}
  29814. * @default null
  29815. */
  29816. this.currentFunctionNode = null;
  29817. /**
  29818. * The builder's context.
  29819. *
  29820. * @type {Object}
  29821. */
  29822. this.context = {
  29823. material: this.material
  29824. };
  29825. /**
  29826. * The builder's cache.
  29827. *
  29828. * @type {NodeCache}
  29829. */
  29830. this.cache = new NodeCache();
  29831. /**
  29832. * Since the {@link NodeBuilder#cache} might be temporarily
  29833. * overwritten by other caches, this member retains the reference
  29834. * to the builder's own cache.
  29835. *
  29836. * @type {NodeCache}
  29837. * @default this.cache
  29838. */
  29839. this.globalCache = this.cache;
  29840. this.flowsData = new WeakMap();
  29841. /**
  29842. * The current shader stage.
  29843. *
  29844. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29845. */
  29846. this.shaderStage = null;
  29847. /**
  29848. * The current build stage.
  29849. *
  29850. * @type {('setup'|'analyze'|'generate')?}
  29851. */
  29852. this.buildStage = null;
  29853. /**
  29854. * Whether comparison in shader code are generated with methods or not.
  29855. *
  29856. * @type {Boolean}
  29857. * @default false
  29858. */
  29859. this.useComparisonMethod = false;
  29860. }
  29861. /**
  29862. * Returns the bind groups of the current renderer.
  29863. *
  29864. * @return {ChainMap} The cache.
  29865. */
  29866. getBindGroupsCache() {
  29867. let bindGroupsCache = rendererCache.get( this.renderer );
  29868. if ( bindGroupsCache === undefined ) {
  29869. bindGroupsCache = new ChainMap();
  29870. rendererCache.set( this.renderer, bindGroupsCache );
  29871. }
  29872. return bindGroupsCache;
  29873. }
  29874. /**
  29875. * Factory method for creating an instance of {@link RenderTarget} with the given
  29876. * dimensions and options.
  29877. *
  29878. * @param {Number} width - The width of the render target.
  29879. * @param {Number} height - The height of the render target.
  29880. * @param {Object} options - The options of the render target.
  29881. * @return {RenderTarget} The render target.
  29882. */
  29883. createRenderTarget( width, height, options ) {
  29884. return new RenderTarget( width, height, options );
  29885. }
  29886. /**
  29887. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29888. * dimensions and options.
  29889. *
  29890. * @param {Number} size - The size of the cube render target.
  29891. * @param {Object} options - The options of the cube render target.
  29892. * @return {CubeRenderTarget} The cube render target.
  29893. */
  29894. createCubeRenderTarget( size, options ) {
  29895. return new CubeRenderTarget( size, options );
  29896. }
  29897. /**
  29898. * Factory method for creating an instance of {@link PMREMGenerator}.
  29899. *
  29900. * @return {PMREMGenerator} The PMREM generator.
  29901. */
  29902. createPMREMGenerator() {
  29903. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29904. return new PMREMGenerator( this.renderer );
  29905. }
  29906. /**
  29907. * Whether the given node is included in the internal array of nodes or not.
  29908. *
  29909. * @param {Node} node - The node to test.
  29910. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29911. */
  29912. includes( node ) {
  29913. return this.nodes.includes( node );
  29914. }
  29915. /**
  29916. * Returns the output struct name which is required by
  29917. * {@link module:OutputStructNode}.
  29918. *
  29919. * @abstract
  29920. * @return {String} The name of the output struct.
  29921. */
  29922. getOutputStructName() {}
  29923. /**
  29924. * Returns a bind group for the given group name and binding.
  29925. *
  29926. * @private
  29927. * @param {String} groupName - The group name.
  29928. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29929. * @return {BindGroup} The bind group
  29930. */
  29931. _getBindGroup( groupName, bindings ) {
  29932. const bindGroupsCache = this.getBindGroupsCache();
  29933. //
  29934. const bindingsArray = [];
  29935. let sharedGroup = true;
  29936. for ( const binding of bindings ) {
  29937. bindingsArray.push( binding );
  29938. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29939. }
  29940. //
  29941. let bindGroup;
  29942. if ( sharedGroup ) {
  29943. bindGroup = bindGroupsCache.get( bindingsArray );
  29944. if ( bindGroup === undefined ) {
  29945. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29946. bindGroupsCache.set( bindingsArray, bindGroup );
  29947. }
  29948. } else {
  29949. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29950. }
  29951. return bindGroup;
  29952. }
  29953. /**
  29954. * Returns an array of node uniform groups for the given group name and shader stage.
  29955. *
  29956. * @param {String} groupName - The group name.
  29957. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29958. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29959. */
  29960. getBindGroupArray( groupName, shaderStage ) {
  29961. const bindings = this.bindings[ shaderStage ];
  29962. let bindGroup = bindings[ groupName ];
  29963. if ( bindGroup === undefined ) {
  29964. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29965. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29966. }
  29967. bindings[ groupName ] = bindGroup = [];
  29968. }
  29969. return bindGroup;
  29970. }
  29971. /**
  29972. * Returns a list bindings of all shader stages separated by groups.
  29973. *
  29974. * @return {Array<BindGroup>} The list of bindings.
  29975. */
  29976. getBindings() {
  29977. let bindingsGroups = this.bindGroups;
  29978. if ( bindingsGroups === null ) {
  29979. const groups = {};
  29980. const bindings = this.bindings;
  29981. for ( const shaderStage of shaderStages ) {
  29982. for ( const groupName in bindings[ shaderStage ] ) {
  29983. const uniforms = bindings[ shaderStage ][ groupName ];
  29984. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29985. groupUniforms.push( ...uniforms );
  29986. }
  29987. }
  29988. bindingsGroups = [];
  29989. for ( const groupName in groups ) {
  29990. const group = groups[ groupName ];
  29991. const bindingsGroup = this._getBindGroup( groupName, group );
  29992. bindingsGroups.push( bindingsGroup );
  29993. }
  29994. this.bindGroups = bindingsGroups;
  29995. }
  29996. return bindingsGroups;
  29997. }
  29998. /**
  29999. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30000. */
  30001. sortBindingGroups() {
  30002. const bindingsGroups = this.getBindings();
  30003. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30004. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30005. const bindingGroup = bindingsGroups[ i ];
  30006. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30007. bindingGroup.index = i;
  30008. }
  30009. }
  30010. /**
  30011. * The builder maintains each node in a hash-based dictionary.
  30012. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30013. *
  30014. * @param {Node} node - The node to add.
  30015. * @param {Number} hash - The hash of the node.
  30016. */
  30017. setHashNode( node, hash ) {
  30018. this.hashNodes[ hash ] = node;
  30019. }
  30020. /**
  30021. * Adds a node to this builder.
  30022. *
  30023. * @param {Node} node - The node to add.
  30024. */
  30025. addNode( node ) {
  30026. if ( this.nodes.includes( node ) === false ) {
  30027. this.nodes.push( node );
  30028. this.setHashNode( node, node.getHash( this ) );
  30029. }
  30030. }
  30031. /**
  30032. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30033. * and need to follow a certain sequence in the calls to work correctly.
  30034. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30035. *
  30036. * @param {Node} node - The node to add.
  30037. */
  30038. addSequentialNode( node ) {
  30039. if ( this.sequentialNodes.includes( node ) === false ) {
  30040. this.sequentialNodes.push( node );
  30041. }
  30042. }
  30043. /**
  30044. * Checks the update types of nodes
  30045. */
  30046. buildUpdateNodes() {
  30047. for ( const node of this.nodes ) {
  30048. const updateType = node.getUpdateType();
  30049. if ( updateType !== NodeUpdateType.NONE ) {
  30050. this.updateNodes.push( node.getSelf() );
  30051. }
  30052. }
  30053. for ( const node of this.sequentialNodes ) {
  30054. const updateBeforeType = node.getUpdateBeforeType();
  30055. const updateAfterType = node.getUpdateAfterType();
  30056. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30057. this.updateBeforeNodes.push( node.getSelf() );
  30058. }
  30059. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30060. this.updateAfterNodes.push( node.getSelf() );
  30061. }
  30062. }
  30063. }
  30064. /**
  30065. * A reference the current node which is the
  30066. * last node in the chain of nodes.
  30067. *
  30068. * @type {Node}
  30069. */
  30070. get currentNode() {
  30071. return this.chaining[ this.chaining.length - 1 ];
  30072. }
  30073. /**
  30074. * Whether the given texture is filtered or not.
  30075. *
  30076. * @param {Texture} texture - The texture to check.
  30077. * @return {Boolean} Whether the given texture is filtered or not.
  30078. */
  30079. isFilteredTexture( texture ) {
  30080. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30081. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30082. }
  30083. /**
  30084. * Adds the given node to the internal node chain.
  30085. * This is used to check recursive calls in node-graph.
  30086. *
  30087. * @param {Node} node - The node to add.
  30088. */
  30089. addChain( node ) {
  30090. /*
  30091. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30092. console.warn( 'Recursive node: ', node );
  30093. }
  30094. */
  30095. this.chaining.push( node );
  30096. }
  30097. /**
  30098. * Removes the given node from the internal node chain.
  30099. *
  30100. * @param {Node} node - The node to remove.
  30101. */
  30102. removeChain( node ) {
  30103. const lastChain = this.chaining.pop();
  30104. if ( lastChain !== node ) {
  30105. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30106. }
  30107. }
  30108. /**
  30109. * Returns the native shader method name for a given generic name. E.g.
  30110. * the method name `textureDimensions` matches the WGSL name but must be
  30111. * resolved to `textureSize` in GLSL.
  30112. *
  30113. * @abstract
  30114. * @param {String} method - The method name to resolve.
  30115. * @return {String} The resolved method name.
  30116. */
  30117. getMethod( method ) {
  30118. return method;
  30119. }
  30120. /**
  30121. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30122. *
  30123. * @param {Number} hash - The hash of the node.
  30124. * @return {Node} The found node.
  30125. */
  30126. getNodeFromHash( hash ) {
  30127. return this.hashNodes[ hash ];
  30128. }
  30129. /**
  30130. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30131. *
  30132. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30133. * @param {Node} node - The node to add.
  30134. * @return {Node} The node.
  30135. */
  30136. addFlow( shaderStage, node ) {
  30137. this.flowNodes[ shaderStage ].push( node );
  30138. return node;
  30139. }
  30140. /**
  30141. * Sets builder's context.
  30142. *
  30143. * @param {Object} context - The context to set.
  30144. */
  30145. setContext( context ) {
  30146. this.context = context;
  30147. }
  30148. /**
  30149. * Returns the builder's current context.
  30150. *
  30151. * @return {Object} The builder's current context.
  30152. */
  30153. getContext() {
  30154. return this.context;
  30155. }
  30156. /**
  30157. * Gets a context used in shader construction that can be shared across different materials.
  30158. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30159. *
  30160. * @return {Object} The builder's current context without material.
  30161. */
  30162. getSharedContext() {
  30163. ({ ...this.context });
  30164. return this.context;
  30165. }
  30166. /**
  30167. * Sets builder's cache.
  30168. *
  30169. * @param {NodeCache} cache - The cache to set.
  30170. */
  30171. setCache( cache ) {
  30172. this.cache = cache;
  30173. }
  30174. /**
  30175. * Returns the builder's current cache.
  30176. *
  30177. * @return {NodeCache} The builder's current cache.
  30178. */
  30179. getCache() {
  30180. return this.cache;
  30181. }
  30182. /**
  30183. * Returns a cache for the given node.
  30184. *
  30185. * @param {Node} node - The node.
  30186. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30187. * @return {NodeCache} The cache.
  30188. */
  30189. getCacheFromNode( node, parent = true ) {
  30190. const data = this.getDataFromNode( node );
  30191. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30192. return data.cache;
  30193. }
  30194. /**
  30195. * Whether the requested feature is available or not.
  30196. *
  30197. * @abstract
  30198. * @param {String} name - The requested feature.
  30199. * @return {Boolean} Whether the requested feature is supported or not.
  30200. */
  30201. isAvailable( /*name*/ ) {
  30202. return false;
  30203. }
  30204. /**
  30205. * Returns the vertexIndex input variable as a native shader string.
  30206. *
  30207. * @abstract
  30208. * @return {String} The instanceIndex shader string.
  30209. */
  30210. getVertexIndex() {
  30211. console.warn( 'Abstract function.' );
  30212. }
  30213. /**
  30214. * Returns the instanceIndex input variable as a native shader string.
  30215. *
  30216. * @abstract
  30217. * @return {String} The instanceIndex shader string.
  30218. */
  30219. getInstanceIndex() {
  30220. console.warn( 'Abstract function.' );
  30221. }
  30222. /**
  30223. * Returns the drawIndex input variable as a native shader string.
  30224. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30225. *
  30226. * @abstract
  30227. * @return {String} The drawIndex shader string.
  30228. */
  30229. getDrawIndex() {
  30230. console.warn( 'Abstract function.' );
  30231. }
  30232. /**
  30233. * Returns the frontFacing input variable as a native shader string.
  30234. *
  30235. * @abstract
  30236. * @return {String} The frontFacing shader string.
  30237. */
  30238. getFrontFacing() {
  30239. console.warn( 'Abstract function.' );
  30240. }
  30241. /**
  30242. * Returns the fragCoord input variable as a native shader string.
  30243. *
  30244. * @abstract
  30245. * @return {String} The fragCoord shader string.
  30246. */
  30247. getFragCoord() {
  30248. console.warn( 'Abstract function.' );
  30249. }
  30250. /**
  30251. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30252. * this method evaluate to `true`, WebGPU to `false`.
  30253. *
  30254. * @abstract
  30255. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30256. */
  30257. isFlipY() {
  30258. return false;
  30259. }
  30260. /**
  30261. * Calling this method increases the usage count for the given node by one.
  30262. *
  30263. * @param {Node} node - The node to increase the usage count for.
  30264. * @return {Number} The updated usage count.
  30265. */
  30266. increaseUsage( node ) {
  30267. const nodeData = this.getDataFromNode( node );
  30268. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30269. return nodeData.usageCount;
  30270. }
  30271. /**
  30272. * Generates a texture sample shader string for the given texture data.
  30273. *
  30274. * @abstract
  30275. * @param {Texture} texture - The texture.
  30276. * @param {String} textureProperty - The texture property name.
  30277. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30278. * @return {String} The generated shader string.
  30279. */
  30280. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30281. console.warn( 'Abstract function.' );
  30282. }
  30283. /**
  30284. * Generates a texture LOD shader string for the given texture data.
  30285. *
  30286. * @abstract
  30287. * @param {Texture} texture - The texture.
  30288. * @param {String} textureProperty - The texture property name.
  30289. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30290. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30291. * @param {String} levelSnippet - Snippet defining the mip level.
  30292. * @return {String} The generated shader string.
  30293. */
  30294. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30295. console.warn( 'Abstract function.' );
  30296. }
  30297. /**
  30298. * Generates the shader string for the given type and value.
  30299. *
  30300. * @param {String} type - The type.
  30301. * @param {Any?} [value=null] - The value.
  30302. * @return {String} The generated value as a shader string.
  30303. */
  30304. generateConst( type, value = null ) {
  30305. if ( value === null ) {
  30306. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30307. else if ( type === 'bool' ) value = false;
  30308. else if ( type === 'color' ) value = new Color();
  30309. else if ( type === 'vec2' ) value = new Vector2();
  30310. else if ( type === 'vec3' ) value = new Vector3();
  30311. else if ( type === 'vec4' ) value = new Vector4();
  30312. }
  30313. if ( type === 'float' ) return toFloat( value );
  30314. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30315. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30316. if ( type === 'bool' ) return value ? 'true' : 'false';
  30317. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30318. const typeLength = this.getTypeLength( type );
  30319. const componentType = this.getComponentType( type );
  30320. const generateConst = value => this.generateConst( componentType, value );
  30321. if ( typeLength === 2 ) {
  30322. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30323. } else if ( typeLength === 3 ) {
  30324. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30325. } else if ( typeLength === 4 ) {
  30326. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30327. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30328. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30329. } else if ( typeLength > 4 ) {
  30330. return `${ this.getType( type ) }()`;
  30331. }
  30332. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30333. }
  30334. /**
  30335. * It might be necessary to convert certain data types to different ones
  30336. * so this method can be used to hide the conversion.
  30337. *
  30338. * @param {String} type - The type.
  30339. * @return {String} The updated type.
  30340. */
  30341. getType( type ) {
  30342. if ( type === 'color' ) return 'vec3';
  30343. return type;
  30344. }
  30345. /**
  30346. * Whether the given attribute name is defined in the geometry or not.
  30347. *
  30348. * @param {String} name - The attribute name.
  30349. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30350. */
  30351. hasGeometryAttribute( name ) {
  30352. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30353. }
  30354. /**
  30355. * Returns a node attribute for the given name and type.
  30356. *
  30357. * @param {String} name - The attribute's name.
  30358. * @param {String} type - The attribute's type.
  30359. * @return {NodeAttribute} The node attribute.
  30360. */
  30361. getAttribute( name, type ) {
  30362. const attributes = this.attributes;
  30363. // find attribute
  30364. for ( const attribute of attributes ) {
  30365. if ( attribute.name === name ) {
  30366. return attribute;
  30367. }
  30368. }
  30369. // create a new if no exist
  30370. const attribute = new NodeAttribute( name, type );
  30371. attributes.push( attribute );
  30372. return attribute;
  30373. }
  30374. /**
  30375. * Returns for the given node and shader stage the property name for the shader.
  30376. *
  30377. * @param {Node} node - The node.
  30378. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30379. * @return {String} The property name.
  30380. */
  30381. getPropertyName( node/*, shaderStage*/ ) {
  30382. return node.name;
  30383. }
  30384. /**
  30385. * Whether the given type is a vector type or not.
  30386. *
  30387. * @param {String} type - The type to check.
  30388. * @return {Boolean} Whether the given type is a vector type or not.
  30389. */
  30390. isVector( type ) {
  30391. return /vec\d/.test( type );
  30392. }
  30393. /**
  30394. * Whether the given type is a matrix type or not.
  30395. *
  30396. * @param {String} type - The type to check.
  30397. * @return {Boolean} Whether the given type is a matrix type or not.
  30398. */
  30399. isMatrix( type ) {
  30400. return /mat\d/.test( type );
  30401. }
  30402. /**
  30403. * Whether the given type is a reference type or not.
  30404. *
  30405. * @param {String} type - The type to check.
  30406. * @return {Boolean} Whether the given type is a reference type or not.
  30407. */
  30408. isReference( type ) {
  30409. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30410. }
  30411. /**
  30412. * Checks if the given texture requires a manual conversion to the working color space.
  30413. *
  30414. * @abstract
  30415. * @param {Texture} texture - The texture to check.
  30416. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30417. */
  30418. needsToWorkingColorSpace( /*texture*/ ) {
  30419. return false;
  30420. }
  30421. /**
  30422. * Returns the component type of a given texture.
  30423. *
  30424. * @param {Texture} texture - The texture.
  30425. * @return {String} The component type.
  30426. */
  30427. getComponentTypeFromTexture( texture ) {
  30428. const type = texture.type;
  30429. if ( texture.isDataTexture ) {
  30430. if ( type === IntType ) return 'int';
  30431. if ( type === UnsignedIntType ) return 'uint';
  30432. }
  30433. return 'float';
  30434. }
  30435. /**
  30436. * Returns the element type for a given type.
  30437. *
  30438. * @param {String} type - The type.
  30439. * @return {String} The element type.
  30440. */
  30441. getElementType( type ) {
  30442. if ( type === 'mat2' ) return 'vec2';
  30443. if ( type === 'mat3' ) return 'vec3';
  30444. if ( type === 'mat4' ) return 'vec4';
  30445. return this.getComponentType( type );
  30446. }
  30447. /**
  30448. * Returns the component type for a given type.
  30449. *
  30450. * @param {String} type - The type.
  30451. * @return {String} The component type.
  30452. */
  30453. getComponentType( type ) {
  30454. type = this.getVectorType( type );
  30455. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30456. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30457. if ( componentType === null ) return null;
  30458. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30459. if ( componentType[ 1 ] === 'i' ) return 'int';
  30460. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30461. return 'float';
  30462. }
  30463. /**
  30464. * Returns the vector type for a given type.
  30465. *
  30466. * @param {String} type - The type.
  30467. * @return {String} The vector type.
  30468. */
  30469. getVectorType( type ) {
  30470. if ( type === 'color' ) return 'vec3';
  30471. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30472. return type;
  30473. }
  30474. /**
  30475. * Returns the data type for the given the length and component type.
  30476. *
  30477. * @param {Number} length - The length.
  30478. * @param {String} [componentType='float'] - The component type.
  30479. * @return {String} The type.
  30480. */
  30481. getTypeFromLength( length, componentType = 'float' ) {
  30482. if ( length === 1 ) return componentType;
  30483. const baseType = getTypeFromLength( length );
  30484. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30485. return prefix + baseType;
  30486. }
  30487. /**
  30488. * Returns the type for a given typed array.
  30489. *
  30490. * @param {TypedArray} array - The typed array.
  30491. * @return {String} The type.
  30492. */
  30493. getTypeFromArray( array ) {
  30494. return typeFromArray.get( array.constructor );
  30495. }
  30496. /**
  30497. * Returns the type for a given buffer attribute.
  30498. *
  30499. * @param {BufferAttribute} attribute - The buffer attribute.
  30500. * @return {String} The type.
  30501. */
  30502. getTypeFromAttribute( attribute ) {
  30503. let dataAttribute = attribute;
  30504. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30505. const array = dataAttribute.array;
  30506. const itemSize = attribute.itemSize;
  30507. const normalized = attribute.normalized;
  30508. let arrayType;
  30509. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30510. arrayType = this.getTypeFromArray( array );
  30511. }
  30512. return this.getTypeFromLength( itemSize, arrayType );
  30513. }
  30514. /**
  30515. * Returns the length for the given data type.
  30516. *
  30517. * @param {String} type - The data type.
  30518. * @return {Number} The length.
  30519. */
  30520. getTypeLength( type ) {
  30521. const vecType = this.getVectorType( type );
  30522. const vecNum = /vec([2-4])/.exec( vecType );
  30523. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30524. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30525. if ( /mat2/.test( type ) === true ) return 4;
  30526. if ( /mat3/.test( type ) === true ) return 9;
  30527. if ( /mat4/.test( type ) === true ) return 16;
  30528. return 0;
  30529. }
  30530. /**
  30531. * Returns the vector type for a given matrix type.
  30532. *
  30533. * @param {String} type - The matrix type.
  30534. * @return {String} The vector type.
  30535. */
  30536. getVectorFromMatrix( type ) {
  30537. return type.replace( 'mat', 'vec' );
  30538. }
  30539. /**
  30540. * For a given type this method changes the component type to the
  30541. * given value. E.g. `vec4` should be changed to the new component type
  30542. * `uint` which results in `uvec4`.
  30543. *
  30544. * @param {String} type - The type.
  30545. * @param {String} newComponentType - The new component type.
  30546. * @return {String} The new type.
  30547. */
  30548. changeComponentType( type, newComponentType ) {
  30549. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30550. }
  30551. /**
  30552. * Returns the integer type pendant for the given type.
  30553. *
  30554. * @param {String} type - The type.
  30555. * @return {String} The integer type.
  30556. */
  30557. getIntegerType( type ) {
  30558. const componentType = this.getComponentType( type );
  30559. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30560. return this.changeComponentType( type, 'int' );
  30561. }
  30562. /**
  30563. * Adds a stack node to the internal stack.
  30564. *
  30565. * @return {StackNode} The added stack node.
  30566. */
  30567. addStack() {
  30568. this.stack = stack( this.stack );
  30569. this.stacks.push( getCurrentStack() || this.stack );
  30570. setCurrentStack( this.stack );
  30571. return this.stack;
  30572. }
  30573. /**
  30574. * Removes the last stack node from the internal stack.
  30575. *
  30576. * @return {StackNode} The removed stack node.
  30577. */
  30578. removeStack() {
  30579. const lastStack = this.stack;
  30580. this.stack = lastStack.parent;
  30581. setCurrentStack( this.stacks.pop() );
  30582. return lastStack;
  30583. }
  30584. /**
  30585. * The builder maintains (cached) data for each node during the building process. This method
  30586. * can be used to get these data for a specific shader stage and cache.
  30587. *
  30588. * @param {Node} node - The node to get the data for.
  30589. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30590. * @param {NodeCache?} cache - An optional cache.
  30591. * @return {Object} The node data.
  30592. */
  30593. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30594. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30595. let nodeData = cache.getData( node );
  30596. if ( nodeData === undefined ) {
  30597. nodeData = {};
  30598. cache.setData( node, nodeData );
  30599. }
  30600. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30601. return nodeData[ shaderStage ];
  30602. }
  30603. /**
  30604. * Returns the properties for the given node and shader stage.
  30605. *
  30606. * @param {Node} node - The node to get the properties for.
  30607. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30608. * @return {Object} The node properties.
  30609. */
  30610. getNodeProperties( node, shaderStage = 'any' ) {
  30611. const nodeData = this.getDataFromNode( node, shaderStage );
  30612. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30613. }
  30614. /**
  30615. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30616. *
  30617. * @param {BufferAttributeNode} node - The buffer attribute node.
  30618. * @param {String} type - The node type.
  30619. * @return {NodeAttribute} The node attribute.
  30620. */
  30621. getBufferAttributeFromNode( node, type ) {
  30622. const nodeData = this.getDataFromNode( node );
  30623. let bufferAttribute = nodeData.bufferAttribute;
  30624. if ( bufferAttribute === undefined ) {
  30625. const index = this.uniforms.index ++;
  30626. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30627. this.bufferAttributes.push( bufferAttribute );
  30628. nodeData.bufferAttribute = bufferAttribute;
  30629. }
  30630. return bufferAttribute;
  30631. }
  30632. /**
  30633. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30634. *
  30635. * @param {OutputStructNode} node - The output struct node.
  30636. * @param {Array<String>} types - The output struct types.
  30637. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30638. * @return {StructTypeNode} The struct type attribute.
  30639. */
  30640. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30641. const nodeData = this.getDataFromNode( node, shaderStage );
  30642. let structType = nodeData.structType;
  30643. if ( structType === undefined ) {
  30644. const index = this.structs.index ++;
  30645. structType = new StructTypeNode( 'StructType' + index, types );
  30646. this.structs[ shaderStage ].push( structType );
  30647. nodeData.structType = structType;
  30648. }
  30649. return structType;
  30650. }
  30651. /**
  30652. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30653. *
  30654. * @param {UniformNode} node - The uniform node.
  30655. * @param {String} type - The uniform type.
  30656. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30657. * @param {String?} name - The name of the uniform.
  30658. * @return {NodeUniform} The node uniform.
  30659. */
  30660. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30661. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30662. let nodeUniform = nodeData.uniform;
  30663. if ( nodeUniform === undefined ) {
  30664. const index = this.uniforms.index ++;
  30665. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30666. this.uniforms[ shaderStage ].push( nodeUniform );
  30667. nodeData.uniform = nodeUniform;
  30668. }
  30669. return nodeUniform;
  30670. }
  30671. /**
  30672. * Returns an instance of {@link NodeVar} for the given variable node.
  30673. *
  30674. * @param {VarNode} node - The variable node.
  30675. * @param {String?} name - The variable's name.
  30676. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30677. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30678. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30679. *
  30680. * @return {NodeVar} The node variable.
  30681. */
  30682. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30683. const nodeData = this.getDataFromNode( node, shaderStage );
  30684. let nodeVar = nodeData.variable;
  30685. if ( nodeVar === undefined ) {
  30686. const idNS = readOnly ? '_const' : '_var';
  30687. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30688. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30689. if ( name === null ) {
  30690. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30691. this.vars[ idNS ] ++;
  30692. }
  30693. nodeVar = new NodeVar( name, type, readOnly );
  30694. if ( ! readOnly ) {
  30695. vars.push( nodeVar );
  30696. }
  30697. nodeData.variable = nodeVar;
  30698. }
  30699. return nodeVar;
  30700. }
  30701. /**
  30702. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30703. *
  30704. * @param {Node} node - The varying node.
  30705. * @return {Boolean} Returns true if deterministic.
  30706. */
  30707. isDeterministic( node ) {
  30708. if ( node.isMathNode ) {
  30709. return this.isDeterministic( node.aNode ) &&
  30710. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30711. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30712. } else if ( node.isOperatorNode ) {
  30713. return this.isDeterministic( node.aNode ) &&
  30714. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30715. } else if ( node.isConstNode ) {
  30716. return true;
  30717. }
  30718. return false;
  30719. }
  30720. /**
  30721. * Returns an instance of {@link NodeVarying} for the given varying node.
  30722. *
  30723. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30724. * @param {String?} name - The varying's name.
  30725. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30726. * @return {NodeVar} The node varying.
  30727. */
  30728. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30729. const nodeData = this.getDataFromNode( node, 'any' );
  30730. let nodeVarying = nodeData.varying;
  30731. if ( nodeVarying === undefined ) {
  30732. const varyings = this.varyings;
  30733. const index = varyings.length;
  30734. if ( name === null ) name = 'nodeVarying' + index;
  30735. nodeVarying = new NodeVarying( name, type );
  30736. varyings.push( nodeVarying );
  30737. nodeData.varying = nodeVarying;
  30738. }
  30739. return nodeVarying;
  30740. }
  30741. /**
  30742. * Returns an instance of {@link NodeCode} for the given code node.
  30743. *
  30744. * @param {CodeNode} node - The code node.
  30745. * @param {String} type - The node type.
  30746. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30747. * @return {NodeCode} The node code.
  30748. */
  30749. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30750. const nodeData = this.getDataFromNode( node );
  30751. let nodeCode = nodeData.code;
  30752. if ( nodeCode === undefined ) {
  30753. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30754. const index = codes.length;
  30755. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30756. codes.push( nodeCode );
  30757. nodeData.code = nodeCode;
  30758. }
  30759. return nodeCode;
  30760. }
  30761. /**
  30762. * Adds a code flow based on the code-block hierarchy.
  30763. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30764. * is only used inside one of these conditionals in the current shader stage.
  30765. *
  30766. * @param {Node} node - The node to add.
  30767. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30768. */
  30769. addFlowCodeHierarchy( node, nodeBlock ) {
  30770. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30771. let needsFlowCode = true;
  30772. let nodeBlockHierarchy = nodeBlock;
  30773. while ( nodeBlockHierarchy ) {
  30774. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30775. needsFlowCode = false;
  30776. break;
  30777. }
  30778. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30779. }
  30780. if ( needsFlowCode ) {
  30781. for ( const flowCode of flowCodes ) {
  30782. this.addLineFlowCode( flowCode );
  30783. }
  30784. }
  30785. }
  30786. /**
  30787. * Add a inline-code to the current flow code-block.
  30788. *
  30789. * @param {Node} node - The node to add.
  30790. * @param {String} code - The code to add.
  30791. * @param {Node} nodeBlock - Current ConditionalNode
  30792. */
  30793. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30794. const nodeData = this.getDataFromNode( node );
  30795. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30796. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30797. flowCodes.push( code );
  30798. codeBlock.set( nodeBlock, true );
  30799. }
  30800. /**
  30801. * Add a inline-code to the current flow.
  30802. *
  30803. * @param {String} code - The code to add.
  30804. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30805. * @return {NodeBuilder} A reference to this node builder.
  30806. */
  30807. addLineFlowCode( code, node = null ) {
  30808. if ( code === '' ) return this;
  30809. if ( node !== null && this.context.nodeBlock ) {
  30810. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30811. }
  30812. code = this.tab + code;
  30813. if ( ! /;\s*$/.test( code ) ) {
  30814. code = code + ';\n';
  30815. }
  30816. this.flow.code += code;
  30817. return this;
  30818. }
  30819. /**
  30820. * Adds a code to the current code flow.
  30821. *
  30822. * @param {String} code - Shader code.
  30823. * @return {NodeBuilder} A reference to this node builder.
  30824. */
  30825. addFlowCode( code ) {
  30826. this.flow.code += code;
  30827. return this;
  30828. }
  30829. /**
  30830. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30831. * Typically used in codes with If,Else.
  30832. *
  30833. * @return {NodeBuilder} A reference to this node builder.
  30834. */
  30835. addFlowTab() {
  30836. this.tab += '\t';
  30837. return this;
  30838. }
  30839. /**
  30840. * Removes a tab.
  30841. *
  30842. * @return {NodeBuilder} A reference to this node builder.
  30843. */
  30844. removeFlowTab() {
  30845. this.tab = this.tab.slice( 0, - 1 );
  30846. return this;
  30847. }
  30848. /**
  30849. * Gets the current flow data based on a Node.
  30850. *
  30851. * @param {Node} node - Node that the flow was started.
  30852. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30853. * @return {Object} The flow data.
  30854. */
  30855. getFlowData( node/*, shaderStage*/ ) {
  30856. return this.flowsData.get( node );
  30857. }
  30858. /**
  30859. * Executes the node flow based on a root node to generate the final shader code.
  30860. *
  30861. * @param {Node} node - The node to execute.
  30862. * @return {Object} The code flow.
  30863. */
  30864. flowNode( node ) {
  30865. const output = node.getNodeType( this );
  30866. const flowData = this.flowChildNode( node, output );
  30867. this.flowsData.set( node, flowData );
  30868. return flowData;
  30869. }
  30870. /**
  30871. * Returns the native shader operator name for a given generic name.
  30872. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30873. *
  30874. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30875. * @return {FunctionNode} The build function node.
  30876. */
  30877. buildFunctionNode( shaderNode ) {
  30878. const fn = new FunctionNode();
  30879. const previous = this.currentFunctionNode;
  30880. this.currentFunctionNode = fn;
  30881. fn.code = this.buildFunctionCode( shaderNode );
  30882. this.currentFunctionNode = previous;
  30883. return fn;
  30884. }
  30885. /**
  30886. * Generates a code flow based on a TSL function: Fn().
  30887. *
  30888. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30889. * @return {Object}
  30890. */
  30891. flowShaderNode( shaderNode ) {
  30892. const layout = shaderNode.layout;
  30893. const inputs = {
  30894. [ Symbol.iterator ]() {
  30895. let index = 0;
  30896. const values = Object.values( this );
  30897. return {
  30898. next: () => ( {
  30899. value: values[ index ],
  30900. done: index ++ >= values.length
  30901. } )
  30902. };
  30903. }
  30904. };
  30905. for ( const input of layout.inputs ) {
  30906. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30907. }
  30908. //
  30909. shaderNode.layout = null;
  30910. const callNode = shaderNode.call( inputs );
  30911. const flowData = this.flowStagesNode( callNode, layout.type );
  30912. shaderNode.layout = layout;
  30913. return flowData;
  30914. }
  30915. /**
  30916. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30917. *
  30918. * @param {Node} node - The node to execute.
  30919. * @param {String?} output - Expected output type. For example 'vec3'.
  30920. * @return {Object}
  30921. */
  30922. flowStagesNode( node, output = null ) {
  30923. const previousFlow = this.flow;
  30924. const previousVars = this.vars;
  30925. const previousCache = this.cache;
  30926. const previousBuildStage = this.buildStage;
  30927. const previousStack = this.stack;
  30928. const flow = {
  30929. code: ''
  30930. };
  30931. this.flow = flow;
  30932. this.vars = {};
  30933. this.cache = new NodeCache();
  30934. this.stack = stack();
  30935. for ( const buildStage of defaultBuildStages ) {
  30936. this.setBuildStage( buildStage );
  30937. flow.result = node.build( this, output );
  30938. }
  30939. flow.vars = this.getVars( this.shaderStage );
  30940. this.flow = previousFlow;
  30941. this.vars = previousVars;
  30942. this.cache = previousCache;
  30943. this.stack = previousStack;
  30944. this.setBuildStage( previousBuildStage );
  30945. return flow;
  30946. }
  30947. /**
  30948. * Returns the native shader operator name for a given generic name.
  30949. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30950. *
  30951. * @abstract
  30952. * @param {String} op - The operator name to resolve.
  30953. * @return {String} The resolved operator name.
  30954. */
  30955. getFunctionOperator( /* op */ ) {
  30956. return null;
  30957. }
  30958. /**
  30959. * Generates a code flow based on a child Node.
  30960. *
  30961. * @param {Node} node - The node to execute.
  30962. * @param {String?} output - Expected output type. For example 'vec3'.
  30963. * @return {Object} The code flow.
  30964. */
  30965. flowChildNode( node, output = null ) {
  30966. const previousFlow = this.flow;
  30967. const flow = {
  30968. code: ''
  30969. };
  30970. this.flow = flow;
  30971. flow.result = node.build( this, output );
  30972. this.flow = previousFlow;
  30973. return flow;
  30974. }
  30975. /**
  30976. * Executes a flow of code in a different stage.
  30977. *
  30978. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30979. * return the value in fragment-stage even if it is being executed in an input fragment.
  30980. *
  30981. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30982. * @param {Node} node - The node to execute.
  30983. * @param {String?} output - Expected output type. For example 'vec3'.
  30984. * @param {String?} propertyName - The property name to assign the result.
  30985. * @return {Object}
  30986. */
  30987. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30988. const previousShaderStage = this.shaderStage;
  30989. this.setShaderStage( shaderStage );
  30990. const flowData = this.flowChildNode( node, output );
  30991. if ( propertyName !== null ) {
  30992. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30993. }
  30994. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30995. this.setShaderStage( previousShaderStage );
  30996. return flowData;
  30997. }
  30998. /**
  30999. * Returns an array holding all node attributes of this node builder.
  31000. *
  31001. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31002. */
  31003. getAttributesArray() {
  31004. return this.attributes.concat( this.bufferAttributes );
  31005. }
  31006. /**
  31007. * Returns the attribute definitions as a shader string for the given shader stage.
  31008. *
  31009. * @abstract
  31010. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31011. * @return {String} The attribute code section.
  31012. */
  31013. getAttributes( /*shaderStage*/ ) {
  31014. console.warn( 'Abstract function.' );
  31015. }
  31016. /**
  31017. * Returns the varying definitions as a shader string for the given shader stage.
  31018. *
  31019. * @abstract
  31020. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31021. * @return {String} The varying code section.
  31022. */
  31023. getVaryings( /*shaderStage*/ ) {
  31024. console.warn( 'Abstract function.' );
  31025. }
  31026. /**
  31027. * Returns a single variable definition as a shader string for the given variable type and name.
  31028. *
  31029. * @param {String} type - The variable's type.
  31030. * @param {String} name - The variable's name.
  31031. * @return {String} The shader string.
  31032. */
  31033. getVar( type, name ) {
  31034. return `${ this.getType( type ) } ${ name }`;
  31035. }
  31036. /**
  31037. * Returns the variable definitions as a shader string for the given shader stage.
  31038. *
  31039. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31040. * @return {String} The variable code section.
  31041. */
  31042. getVars( shaderStage ) {
  31043. let snippet = '';
  31044. const vars = this.vars[ shaderStage ];
  31045. if ( vars !== undefined ) {
  31046. for ( const variable of vars ) {
  31047. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31048. }
  31049. }
  31050. return snippet;
  31051. }
  31052. /**
  31053. * Returns the uniform definitions as a shader string for the given shader stage.
  31054. *
  31055. * @abstract
  31056. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31057. * @return {String} The uniform code section.
  31058. */
  31059. getUniforms( /*shaderStage*/ ) {
  31060. console.warn( 'Abstract function.' );
  31061. }
  31062. /**
  31063. * Returns the native code definitions as a shader string for the given shader stage.
  31064. *
  31065. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31066. * @return {String} The native code section.
  31067. */
  31068. getCodes( shaderStage ) {
  31069. const codes = this.codes[ shaderStage ];
  31070. let code = '';
  31071. if ( codes !== undefined ) {
  31072. for ( const nodeCode of codes ) {
  31073. code += nodeCode.code + '\n';
  31074. }
  31075. }
  31076. return code;
  31077. }
  31078. /**
  31079. * Returns the hash of this node builder.
  31080. *
  31081. * @return {String} The hash.
  31082. */
  31083. getHash() {
  31084. return this.vertexShader + this.fragmentShader + this.computeShader;
  31085. }
  31086. /**
  31087. * Sets the current shader stage.
  31088. *
  31089. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31090. */
  31091. setShaderStage( shaderStage ) {
  31092. this.shaderStage = shaderStage;
  31093. }
  31094. /**
  31095. * Returns the current shader stage.
  31096. *
  31097. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31098. */
  31099. getShaderStage() {
  31100. return this.shaderStage;
  31101. }
  31102. /**
  31103. * Sets the current build stage.
  31104. *
  31105. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31106. */
  31107. setBuildStage( buildStage ) {
  31108. this.buildStage = buildStage;
  31109. }
  31110. /**
  31111. * Returns the current build stage.
  31112. *
  31113. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31114. */
  31115. getBuildStage() {
  31116. return this.buildStage;
  31117. }
  31118. /**
  31119. * Controls the code build of the shader stages.
  31120. *
  31121. * @abstract
  31122. */
  31123. buildCode() {
  31124. console.warn( 'Abstract function.' );
  31125. }
  31126. /**
  31127. * Central build method which controls the build for the given object.
  31128. *
  31129. * @return {NodeBuilder} A reference to this node builder.
  31130. */
  31131. build() {
  31132. const { object, material, renderer } = this;
  31133. if ( material !== null ) {
  31134. let nodeMaterial = renderer.library.fromMaterial( material );
  31135. if ( nodeMaterial === null ) {
  31136. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31137. nodeMaterial = new NodeMaterial();
  31138. }
  31139. nodeMaterial.build( this );
  31140. } else {
  31141. this.addFlow( 'compute', object );
  31142. }
  31143. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31144. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31145. // generate() -> stage 3: generate shader
  31146. for ( const buildStage of defaultBuildStages ) {
  31147. this.setBuildStage( buildStage );
  31148. if ( this.context.vertex && this.context.vertex.isNode ) {
  31149. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31150. }
  31151. for ( const shaderStage of shaderStages ) {
  31152. this.setShaderStage( shaderStage );
  31153. const flowNodes = this.flowNodes[ shaderStage ];
  31154. for ( const node of flowNodes ) {
  31155. if ( buildStage === 'generate' ) {
  31156. this.flowNode( node );
  31157. } else {
  31158. node.build( this );
  31159. }
  31160. }
  31161. }
  31162. }
  31163. this.setBuildStage( null );
  31164. this.setShaderStage( null );
  31165. // stage 4: build code for a specific output
  31166. this.buildCode();
  31167. this.buildUpdateNodes();
  31168. return this;
  31169. }
  31170. /**
  31171. * Returns a uniform representation which is later used for UBO generation and rendering.
  31172. *
  31173. * @param {NodeUniform} uniformNode - The uniform node.
  31174. * @param {String} type - The requested type.
  31175. * @return {Uniform} The uniform.
  31176. */
  31177. getNodeUniform( uniformNode, type ) {
  31178. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31179. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31180. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31181. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31182. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31183. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31184. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31185. throw new Error( `Uniform "${type}" not declared.` );
  31186. }
  31187. /**
  31188. * Formats the given shader snippet from a given type into another one. E.g.
  31189. * this method might be used to convert a simple float string `"1.0"` into a
  31190. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31191. *
  31192. * @param {String} snippet - The shader snippet.
  31193. * @param {String} fromType - The source type.
  31194. * @param {String} toType - The target type.
  31195. * @return {String} The updated shader string.
  31196. */
  31197. format( snippet, fromType, toType ) {
  31198. fromType = this.getVectorType( fromType );
  31199. toType = this.getVectorType( toType );
  31200. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31201. return snippet;
  31202. }
  31203. const fromTypeLength = this.getTypeLength( fromType );
  31204. const toTypeLength = this.getTypeLength( toType );
  31205. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31206. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31207. }
  31208. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31209. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31210. }
  31211. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31212. // @TODO: ignore for now
  31213. return snippet;
  31214. }
  31215. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31216. // @TODO: ignore for now
  31217. return snippet;
  31218. }
  31219. if ( fromTypeLength === toTypeLength ) {
  31220. return `${ this.getType( toType ) }( ${ snippet } )`;
  31221. }
  31222. if ( fromTypeLength > toTypeLength ) {
  31223. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31224. }
  31225. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31226. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31227. }
  31228. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31229. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31230. }
  31231. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31232. // convert a number value to vector type, e.g:
  31233. // vec3( 1u ) -> vec3( float( 1u ) )
  31234. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31235. }
  31236. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31237. }
  31238. /**
  31239. * Returns a signature with the engine's current revision.
  31240. *
  31241. * @return {String} The signature.
  31242. */
  31243. getSignature() {
  31244. return `// Three.js r${ REVISION } - Node System\n`;
  31245. }
  31246. // deprecated
  31247. /**
  31248. * @function
  31249. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31250. *
  31251. * @param {String} [type='NodeMaterial'] - The node material type.
  31252. * @throws {Error}
  31253. */
  31254. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31255. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31256. }
  31257. }
  31258. /**
  31259. * Management class for updating nodes. The module tracks metrics like
  31260. * the elapsed time, delta time, the render and frame ID to correctly
  31261. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31262. * and {@link Node#updateAfter} depending on the node's configuration.
  31263. */
  31264. class NodeFrame {
  31265. /**
  31266. * Constructs a new node fame.
  31267. */
  31268. constructor() {
  31269. /**
  31270. * The elapsed time in seconds.
  31271. *
  31272. * @type {Number}
  31273. * @default 0
  31274. */
  31275. this.time = 0;
  31276. /**
  31277. * The delta time in seconds.
  31278. *
  31279. * @type {Number}
  31280. * @default 0
  31281. */
  31282. this.deltaTime = 0;
  31283. /**
  31284. * The frame ID.
  31285. *
  31286. * @type {Number}
  31287. * @default 0
  31288. */
  31289. this.frameId = 0;
  31290. /**
  31291. * The render ID.
  31292. *
  31293. * @type {Number}
  31294. * @default 0
  31295. */
  31296. this.renderId = 0;
  31297. /**
  31298. * Used to control the {@link Node#update} call.
  31299. *
  31300. * @type {WeakMap<Node, Object>}
  31301. */
  31302. this.updateMap = new WeakMap();
  31303. /**
  31304. * Used to control the {@link Node#updateBefore} call.
  31305. *
  31306. * @type {WeakMap<Node, Object>}
  31307. */
  31308. this.updateBeforeMap = new WeakMap();
  31309. /**
  31310. * Used to control the {@link Node#updateAfter} call.
  31311. *
  31312. * @type {WeakMap<Node, Object>}
  31313. */
  31314. this.updateAfterMap = new WeakMap();
  31315. /**
  31316. * A reference to the current renderer.
  31317. *
  31318. * @type {Renderer?}
  31319. * @default null
  31320. */
  31321. this.renderer = null;
  31322. /**
  31323. * A reference to the current material.
  31324. *
  31325. * @type {Material?}
  31326. * @default null
  31327. */
  31328. this.material = null;
  31329. /**
  31330. * A reference to the current camera.
  31331. *
  31332. * @type {Camera?}
  31333. * @default null
  31334. */
  31335. this.camera = null;
  31336. /**
  31337. * A reference to the current 3D object.
  31338. *
  31339. * @type {Object3D?}
  31340. * @default null
  31341. */
  31342. this.object = null;
  31343. /**
  31344. * A reference to the current scene.
  31345. *
  31346. * @type {Scene?}
  31347. * @default null
  31348. */
  31349. this.scene = null;
  31350. }
  31351. /**
  31352. * Returns a dictionary for a given node and update map which
  31353. * is used to correctly call node update methods per frame or render.
  31354. *
  31355. * @private
  31356. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31357. * @param {Node} nodeRef - The reference to the current node.
  31358. * @return {Object<String,WeakMap>} The dictionary.
  31359. */
  31360. _getMaps( referenceMap, nodeRef ) {
  31361. let maps = referenceMap.get( nodeRef );
  31362. if ( maps === undefined ) {
  31363. maps = {
  31364. renderMap: new WeakMap(),
  31365. frameMap: new WeakMap()
  31366. };
  31367. referenceMap.set( nodeRef, maps );
  31368. }
  31369. return maps;
  31370. }
  31371. /**
  31372. * This method executes the {@link Node#updateBefore} for the given node.
  31373. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31374. * is only executed once per frame, render or object depending on the update
  31375. * type.
  31376. *
  31377. * @param {Node} node - The node that should be updated.
  31378. */
  31379. updateBeforeNode( node ) {
  31380. const updateType = node.getUpdateBeforeType();
  31381. const reference = node.updateReference( this );
  31382. if ( updateType === NodeUpdateType.FRAME ) {
  31383. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31384. if ( frameMap.get( reference ) !== this.frameId ) {
  31385. if ( node.updateBefore( this ) !== false ) {
  31386. frameMap.set( reference, this.frameId );
  31387. }
  31388. }
  31389. } else if ( updateType === NodeUpdateType.RENDER ) {
  31390. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31391. if ( renderMap.get( reference ) !== this.renderId ) {
  31392. if ( node.updateBefore( this ) !== false ) {
  31393. renderMap.set( reference, this.renderId );
  31394. }
  31395. }
  31396. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31397. node.updateBefore( this );
  31398. }
  31399. }
  31400. /**
  31401. * This method executes the {@link Node#updateAfter} for the given node.
  31402. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31403. * is only executed once per frame, render or object depending on the update
  31404. * type.
  31405. *
  31406. * @param {Node} node - The node that should be updated.
  31407. */
  31408. updateAfterNode( node ) {
  31409. const updateType = node.getUpdateAfterType();
  31410. const reference = node.updateReference( this );
  31411. if ( updateType === NodeUpdateType.FRAME ) {
  31412. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31413. if ( frameMap.get( reference ) !== this.frameId ) {
  31414. if ( node.updateAfter( this ) !== false ) {
  31415. frameMap.set( reference, this.frameId );
  31416. }
  31417. }
  31418. } else if ( updateType === NodeUpdateType.RENDER ) {
  31419. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31420. if ( renderMap.get( reference ) !== this.renderId ) {
  31421. if ( node.updateAfter( this ) !== false ) {
  31422. renderMap.set( reference, this.renderId );
  31423. }
  31424. }
  31425. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31426. node.updateAfter( this );
  31427. }
  31428. }
  31429. /**
  31430. * This method executes the {@link Node#update} for the given node.
  31431. * It makes sure {@link Node#updateType} is honored meaning the update
  31432. * is only executed once per frame, render or object depending on the update
  31433. * type.
  31434. *
  31435. * @param {Node} node - The node that should be updated.
  31436. */
  31437. updateNode( node ) {
  31438. const updateType = node.getUpdateType();
  31439. const reference = node.updateReference( this );
  31440. if ( updateType === NodeUpdateType.FRAME ) {
  31441. const { frameMap } = this._getMaps( this.updateMap, reference );
  31442. if ( frameMap.get( reference ) !== this.frameId ) {
  31443. if ( node.update( this ) !== false ) {
  31444. frameMap.set( reference, this.frameId );
  31445. }
  31446. }
  31447. } else if ( updateType === NodeUpdateType.RENDER ) {
  31448. const { renderMap } = this._getMaps( this.updateMap, reference );
  31449. if ( renderMap.get( reference ) !== this.renderId ) {
  31450. if ( node.update( this ) !== false ) {
  31451. renderMap.set( reference, this.renderId );
  31452. }
  31453. }
  31454. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31455. node.update( this );
  31456. }
  31457. }
  31458. /**
  31459. * Updates the internal state of the node frame. This method is
  31460. * called by the renderer in its internal animation loop.
  31461. */
  31462. update() {
  31463. this.frameId ++;
  31464. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31465. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31466. this.lastTime = performance.now();
  31467. this.time += this.deltaTime;
  31468. }
  31469. }
  31470. /**
  31471. * Describes the input of a {@link NodeFunction}.
  31472. */
  31473. class NodeFunctionInput {
  31474. /**
  31475. * Constructs a new node function input.
  31476. *
  31477. * @param {String} type - The input type.
  31478. * @param {String} name - The input name.
  31479. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31480. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31481. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31482. */
  31483. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31484. /**
  31485. * The input type.
  31486. *
  31487. * @type {String}
  31488. */
  31489. this.type = type;
  31490. /**
  31491. * The input name.
  31492. *
  31493. * @type {String}
  31494. */
  31495. this.name = name;
  31496. /**
  31497. * If the input is an Array, count will be the length.
  31498. *
  31499. * @type {Number?}
  31500. * @default null
  31501. */
  31502. this.count = count;
  31503. /**
  31504. *The parameter qualifier (only relevant for GLSL).
  31505. *
  31506. * @type {('in'|'out'|'inout')}
  31507. * @default ''
  31508. */
  31509. this.qualifier = qualifier;
  31510. /**
  31511. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31512. *
  31513. * @type {Boolean}
  31514. * @default false
  31515. */
  31516. this.isConst = isConst;
  31517. }
  31518. }
  31519. NodeFunctionInput.isNodeFunctionInput = true;
  31520. /**
  31521. * Module for representing directional lights as nodes.
  31522. *
  31523. * @augments AnalyticLightNode
  31524. */
  31525. class DirectionalLightNode extends AnalyticLightNode {
  31526. static get type() {
  31527. return 'DirectionalLightNode';
  31528. }
  31529. /**
  31530. * Constructs a new directional light node.
  31531. *
  31532. * @param {DirectionalLight?} [light=null] - The directional light source.
  31533. */
  31534. constructor( light = null ) {
  31535. super( light );
  31536. }
  31537. setup( builder ) {
  31538. super.setup( builder );
  31539. const lightingModel = builder.context.lightingModel;
  31540. const lightColor = this.colorNode;
  31541. const lightDirection = lightTargetDirection( this.light );
  31542. const reflectedLight = builder.context.reflectedLight;
  31543. lightingModel.direct( {
  31544. lightDirection,
  31545. lightColor,
  31546. reflectedLight
  31547. }, builder.stack, builder );
  31548. }
  31549. }
  31550. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31551. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31552. let _ltcLib = null;
  31553. /**
  31554. * Module for representing rect area lights as nodes.
  31555. *
  31556. * @augments AnalyticLightNode
  31557. */
  31558. class RectAreaLightNode extends AnalyticLightNode {
  31559. static get type() {
  31560. return 'RectAreaLightNode';
  31561. }
  31562. /**
  31563. * Constructs a new rect area light node.
  31564. *
  31565. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31566. */
  31567. constructor( light = null ) {
  31568. super( light );
  31569. /**
  31570. * Uniform node representing the half height of the are light.
  31571. *
  31572. * @type {UniformNode<vec3>}
  31573. */
  31574. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31575. /**
  31576. * Uniform node representing the half width of the are light.
  31577. *
  31578. * @type {UniformNode<vec3>}
  31579. */
  31580. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31581. /**
  31582. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31583. * relies on `viewMatrix` which might vary per render call.
  31584. *
  31585. * @type {String}
  31586. * @default 'render'
  31587. */
  31588. this.updateType = NodeUpdateType.RENDER;
  31589. }
  31590. /**
  31591. * Overwritten to updated rect area light specific uniforms.
  31592. *
  31593. * @param {NodeFrame} frame - A reference to the current node frame.
  31594. */
  31595. update( frame ) {
  31596. super.update( frame );
  31597. const { light } = this;
  31598. const viewMatrix = frame.camera.matrixWorldInverse;
  31599. _matrix42.identity();
  31600. _matrix41.copy( light.matrixWorld );
  31601. _matrix41.premultiply( viewMatrix );
  31602. _matrix42.extractRotation( _matrix41 );
  31603. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31604. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31605. this.halfWidth.value.applyMatrix4( _matrix42 );
  31606. this.halfHeight.value.applyMatrix4( _matrix42 );
  31607. }
  31608. setup( builder ) {
  31609. super.setup( builder );
  31610. let ltc_1, ltc_2;
  31611. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31612. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31613. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31614. } else {
  31615. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31616. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31617. }
  31618. const { colorNode, light } = this;
  31619. const lightingModel = builder.context.lightingModel;
  31620. const lightPosition = lightViewPosition( light );
  31621. const reflectedLight = builder.context.reflectedLight;
  31622. lightingModel.directRectArea( {
  31623. lightColor: colorNode,
  31624. lightPosition,
  31625. halfWidth: this.halfWidth,
  31626. halfHeight: this.halfHeight,
  31627. reflectedLight,
  31628. ltc_1,
  31629. ltc_2
  31630. }, builder.stack, builder );
  31631. }
  31632. /**
  31633. * Used to configure the internal BRDF approximation texture data.
  31634. *
  31635. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31636. */
  31637. static setLTC( ltc ) {
  31638. _ltcLib = ltc;
  31639. }
  31640. }
  31641. /**
  31642. * Module for representing spot lights as nodes.
  31643. *
  31644. * @augments AnalyticLightNode
  31645. */
  31646. class SpotLightNode extends AnalyticLightNode {
  31647. static get type() {
  31648. return 'SpotLightNode';
  31649. }
  31650. /**
  31651. * Constructs a new spot light node.
  31652. *
  31653. * @param {SpotLight?} [light=null] - The spot light source.
  31654. */
  31655. constructor( light = null ) {
  31656. super( light );
  31657. /**
  31658. * Uniform node representing the cone cosine.
  31659. *
  31660. * @type {UniformNode<float>}
  31661. */
  31662. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31663. /**
  31664. * Uniform node representing the penumbra cosine.
  31665. *
  31666. * @type {UniformNode<float>}
  31667. */
  31668. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31669. /**
  31670. * Uniform node representing the cutoff distance.
  31671. *
  31672. * @type {UniformNode<float>}
  31673. */
  31674. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31675. /**
  31676. * Uniform node representing the decay exponent.
  31677. *
  31678. * @type {UniformNode<float>}
  31679. */
  31680. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31681. }
  31682. /**
  31683. * Overwritten to updated spot light specific uniforms.
  31684. *
  31685. * @param {NodeFrame} frame - A reference to the current node frame.
  31686. */
  31687. update( frame ) {
  31688. super.update( frame );
  31689. const { light } = this;
  31690. this.coneCosNode.value = Math.cos( light.angle );
  31691. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31692. this.cutoffDistanceNode.value = light.distance;
  31693. this.decayExponentNode.value = light.decay;
  31694. }
  31695. /**
  31696. * Computes the spot attenuation for the given angle.
  31697. *
  31698. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31699. * @return {Node<float>} The spot attenuation.
  31700. */
  31701. getSpotAttenuation( angleCosine ) {
  31702. const { coneCosNode, penumbraCosNode } = this;
  31703. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31704. }
  31705. setup( builder ) {
  31706. super.setup( builder );
  31707. const lightingModel = builder.context.lightingModel;
  31708. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31709. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31710. const lightDirection = lVector.normalize();
  31711. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31712. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31713. const lightDistance = lVector.length();
  31714. const lightAttenuation = getDistanceAttenuation( {
  31715. lightDistance,
  31716. cutoffDistance: cutoffDistanceNode,
  31717. decayExponent: decayExponentNode
  31718. } );
  31719. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31720. if ( light.map ) {
  31721. const spotLightCoord = lightProjectionUV( light );
  31722. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31723. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31724. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31725. }
  31726. const reflectedLight = builder.context.reflectedLight;
  31727. lightingModel.direct( {
  31728. lightDirection,
  31729. lightColor,
  31730. reflectedLight
  31731. }, builder.stack, builder );
  31732. }
  31733. }
  31734. /**
  31735. * An IES version of the default spot light node.
  31736. *
  31737. * @augments SpotLightNode
  31738. */
  31739. class IESSpotLightNode extends SpotLightNode {
  31740. static get type() {
  31741. return 'IESSpotLightNode';
  31742. }
  31743. /**
  31744. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31745. *
  31746. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31747. * @return {Node<float>} The spot attenuation.
  31748. */
  31749. getSpotAttenuation( angleCosine ) {
  31750. const iesMap = this.light.iesMap;
  31751. let spotAttenuation = null;
  31752. if ( iesMap && iesMap.isTexture === true ) {
  31753. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31754. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31755. } else {
  31756. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31757. }
  31758. return spotAttenuation;
  31759. }
  31760. }
  31761. /**
  31762. * Module for representing ambient lights as nodes.
  31763. *
  31764. * @augments AnalyticLightNode
  31765. */
  31766. class AmbientLightNode extends AnalyticLightNode {
  31767. static get type() {
  31768. return 'AmbientLightNode';
  31769. }
  31770. /**
  31771. * Constructs a new ambient light node.
  31772. *
  31773. * @param {AmbientLight?} [light=null] - The ambient light source.
  31774. */
  31775. constructor( light = null ) {
  31776. super( light );
  31777. }
  31778. setup( { context } ) {
  31779. context.irradiance.addAssign( this.colorNode );
  31780. }
  31781. }
  31782. /**
  31783. * Module for representing hemisphere lights as nodes.
  31784. *
  31785. * @augments AnalyticLightNode
  31786. */
  31787. class HemisphereLightNode extends AnalyticLightNode {
  31788. static get type() {
  31789. return 'HemisphereLightNode';
  31790. }
  31791. /**
  31792. * Constructs a new hemisphere light node.
  31793. *
  31794. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31795. */
  31796. constructor( light = null ) {
  31797. super( light );
  31798. /**
  31799. * Uniform node representing the light's position.
  31800. *
  31801. * @type {UniformNode<vec3>}
  31802. */
  31803. this.lightPositionNode = lightPosition( light );
  31804. /**
  31805. * A node representing the light's direction.
  31806. *
  31807. * @type {Node<vec3>}
  31808. */
  31809. this.lightDirectionNode = this.lightPositionNode.normalize();
  31810. /**
  31811. * Uniform node representing the light's ground color.
  31812. *
  31813. * @type {UniformNode<vec3>}
  31814. */
  31815. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31816. }
  31817. /**
  31818. * Overwritten to updated hemisphere light specific uniforms.
  31819. *
  31820. * @param {NodeFrame} frame - A reference to the current node frame.
  31821. */
  31822. update( frame ) {
  31823. const { light } = this;
  31824. super.update( frame );
  31825. this.lightPositionNode.object3d = light;
  31826. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31827. }
  31828. setup( builder ) {
  31829. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31830. const dotNL = normalView.dot( lightDirectionNode );
  31831. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31832. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31833. builder.context.irradiance.addAssign( irradiance );
  31834. }
  31835. }
  31836. /**
  31837. * Module for representing light probes as nodes.
  31838. *
  31839. * @augments AnalyticLightNode
  31840. */
  31841. class LightProbeNode extends AnalyticLightNode {
  31842. static get type() {
  31843. return 'LightProbeNode';
  31844. }
  31845. /**
  31846. * Constructs a new light probe node.
  31847. *
  31848. * @param {LightProbe?} [light=null] - The light probe.
  31849. */
  31850. constructor( light = null ) {
  31851. super( light );
  31852. const array = [];
  31853. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31854. /**
  31855. * Light probe represented as a uniform of spherical harmonics.
  31856. *
  31857. * @type {UniformArrayNode}
  31858. */
  31859. this.lightProbe = uniformArray( array );
  31860. }
  31861. /**
  31862. * Overwritten to updated light probe specific uniforms.
  31863. *
  31864. * @param {NodeFrame} frame - A reference to the current node frame.
  31865. */
  31866. update( frame ) {
  31867. const { light } = this;
  31868. super.update( frame );
  31869. //
  31870. for ( let i = 0; i < 9; i ++ ) {
  31871. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31872. }
  31873. }
  31874. setup( builder ) {
  31875. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31876. builder.context.irradiance.addAssign( irradiance );
  31877. }
  31878. }
  31879. /**
  31880. * Base class for node parsers. A derived parser must be implemented
  31881. * for each supported native shader language.
  31882. */
  31883. class NodeParser {
  31884. /**
  31885. * The method parses the given native code an returns a node function.
  31886. *
  31887. * @abstract
  31888. * @param {String} source - The native shader code.
  31889. * @return {NodeFunction} A node function.
  31890. */
  31891. parseFunction( /*source*/ ) {
  31892. console.warn( 'Abstract function.' );
  31893. }
  31894. }
  31895. /**
  31896. * Base class for node functions. A derived module must be implemented
  31897. * for each supported native shader language. Similar to other `Node*` modules,
  31898. * this class is only relevant during the building process and not used
  31899. * in user-level code.
  31900. */
  31901. class NodeFunction {
  31902. /**
  31903. * Constructs a new node function.
  31904. *
  31905. * @param {String} type - The node type. This type is the return type of the node function.
  31906. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31907. * @param {String} [name=''] - The function's name.
  31908. * @param {String} [precision=''] - The precision qualifier.
  31909. */
  31910. constructor( type, inputs, name = '', precision = '' ) {
  31911. /**
  31912. * The node type. This type is the return type of the node function.
  31913. *
  31914. * @type {String}
  31915. */
  31916. this.type = type;
  31917. /**
  31918. * The function's inputs.
  31919. *
  31920. * @type {Array<NodeFunctionInput>}
  31921. */
  31922. this.inputs = inputs;
  31923. /**
  31924. * The name of the uniform.
  31925. *
  31926. * @type {String}
  31927. * @default ''
  31928. */
  31929. this.name = name;
  31930. /**
  31931. * The precision qualifier.
  31932. *
  31933. * @type {String}
  31934. * @default ''
  31935. */
  31936. this.precision = precision;
  31937. }
  31938. /**
  31939. * This method returns the native code of the node function.
  31940. *
  31941. * @abstract
  31942. * @param {String} name - The function's name.
  31943. * @return {String} A shader code.
  31944. */
  31945. getCode( /*name = this.name*/ ) {
  31946. console.warn( 'Abstract function.' );
  31947. }
  31948. }
  31949. NodeFunction.isNodeFunction = true;
  31950. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31951. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31952. const pragmaMain = '#pragma main';
  31953. const parse$1 = ( source ) => {
  31954. source = source.trim();
  31955. const pragmaMainIndex = source.indexOf( pragmaMain );
  31956. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31957. const declaration = mainCode.match( declarationRegexp$1 );
  31958. if ( declaration !== null && declaration.length === 5 ) {
  31959. // tokenizer
  31960. const inputsCode = declaration[ 4 ];
  31961. const propsMatches = [];
  31962. let nameMatch = null;
  31963. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31964. propsMatches.push( nameMatch );
  31965. }
  31966. // parser
  31967. const inputs = [];
  31968. let i = 0;
  31969. while ( i < propsMatches.length ) {
  31970. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31971. if ( isConst === true ) {
  31972. i ++;
  31973. }
  31974. let qualifier = propsMatches[ i ][ 0 ];
  31975. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31976. i ++;
  31977. } else {
  31978. qualifier = '';
  31979. }
  31980. const type = propsMatches[ i ++ ][ 0 ];
  31981. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31982. if ( Number.isNaN( count ) === false ) i ++;
  31983. else count = null;
  31984. const name = propsMatches[ i ++ ][ 0 ];
  31985. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31986. }
  31987. //
  31988. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31989. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31990. const type = declaration[ 2 ];
  31991. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31992. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31993. return {
  31994. type,
  31995. inputs,
  31996. name,
  31997. precision,
  31998. inputsCode,
  31999. blockCode,
  32000. headerCode
  32001. };
  32002. } else {
  32003. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32004. }
  32005. };
  32006. /**
  32007. * This class represents a GLSL node function.
  32008. *
  32009. * @augments NodeFunction
  32010. */
  32011. class GLSLNodeFunction extends NodeFunction {
  32012. /**
  32013. * Constructs a new GLSL node function.
  32014. *
  32015. * @param {String} source - The GLSL source.
  32016. */
  32017. constructor( source ) {
  32018. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32019. super( type, inputs, name, precision );
  32020. this.inputsCode = inputsCode;
  32021. this.blockCode = blockCode;
  32022. this.headerCode = headerCode;
  32023. }
  32024. /**
  32025. * This method returns the GLSL code of the node function.
  32026. *
  32027. * @param {String} [name=this.name] - The function's name.
  32028. * @return {String} The shader code.
  32029. */
  32030. getCode( name = this.name ) {
  32031. let code;
  32032. const blockCode = this.blockCode;
  32033. if ( blockCode !== '' ) {
  32034. const { type, inputsCode, headerCode, precision } = this;
  32035. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32036. if ( precision !== '' ) {
  32037. declarationCode = `${ precision } ${ declarationCode }`;
  32038. }
  32039. code = headerCode + declarationCode + blockCode;
  32040. } else {
  32041. // interface function
  32042. code = '';
  32043. }
  32044. return code;
  32045. }
  32046. }
  32047. /**
  32048. * A GLSL node parser.
  32049. *
  32050. * @augments NodeParser
  32051. */
  32052. class GLSLNodeParser extends NodeParser {
  32053. /**
  32054. * The method parses the given GLSL code an returns a node function.
  32055. *
  32056. * @param {String} source - The GLSL code.
  32057. * @return {GLSLNodeFunction} A node function.
  32058. */
  32059. parseFunction( source ) {
  32060. return new GLSLNodeFunction( source );
  32061. }
  32062. }
  32063. const _outputNodeMap = new WeakMap();
  32064. const _chainKeys$2 = [];
  32065. const _cacheKeyValues = [];
  32066. /**
  32067. * This renderer module manages node-related objects and is the
  32068. * primary interface between the renderer and the node system.
  32069. *
  32070. * @private
  32071. * @augments DataMap
  32072. */
  32073. class Nodes extends DataMap {
  32074. /**
  32075. * Constructs a new nodes management component.
  32076. *
  32077. * @param {Renderer} renderer - The renderer.
  32078. * @param {Backend} backend - The renderer's backend.
  32079. */
  32080. constructor( renderer, backend ) {
  32081. super();
  32082. /**
  32083. * The renderer.
  32084. *
  32085. * @type {Renderer}
  32086. */
  32087. this.renderer = renderer;
  32088. /**
  32089. * The renderer's backend.
  32090. *
  32091. * @type {Backend}
  32092. */
  32093. this.backend = backend;
  32094. /**
  32095. * The node frame.
  32096. *
  32097. * @type {Renderer}
  32098. */
  32099. this.nodeFrame = new NodeFrame();
  32100. /**
  32101. * A cache for managing node builder states.
  32102. *
  32103. * @type {Map<Number,NodeBuilderState>}
  32104. */
  32105. this.nodeBuilderCache = new Map();
  32106. /**
  32107. * A cache for managing data cache key data.
  32108. *
  32109. * @type {ChainMap}
  32110. */
  32111. this.callHashCache = new ChainMap();
  32112. /**
  32113. * A cache for managing node uniforms group data.
  32114. *
  32115. * @type {ChainMap}
  32116. */
  32117. this.groupsData = new ChainMap();
  32118. /**
  32119. * A cache for managing node objects of
  32120. * scene properties like fog or environments.
  32121. *
  32122. * @type {Object<String,WeakMap>}
  32123. */
  32124. this.cacheLib = {};
  32125. }
  32126. /**
  32127. * Returns `true` if the given node uniforms group must be updated or not.
  32128. *
  32129. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32130. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32131. */
  32132. updateGroup( nodeUniformsGroup ) {
  32133. const groupNode = nodeUniformsGroup.groupNode;
  32134. const name = groupNode.name;
  32135. // objectGroup is always updated
  32136. if ( name === objectGroup.name ) return true;
  32137. // renderGroup is updated once per render/compute call
  32138. if ( name === renderGroup.name ) {
  32139. const uniformsGroupData = this.get( nodeUniformsGroup );
  32140. const renderId = this.nodeFrame.renderId;
  32141. if ( uniformsGroupData.renderId !== renderId ) {
  32142. uniformsGroupData.renderId = renderId;
  32143. return true;
  32144. }
  32145. return false;
  32146. }
  32147. // frameGroup is updated once per frame
  32148. if ( name === frameGroup.name ) {
  32149. const uniformsGroupData = this.get( nodeUniformsGroup );
  32150. const frameId = this.nodeFrame.frameId;
  32151. if ( uniformsGroupData.frameId !== frameId ) {
  32152. uniformsGroupData.frameId = frameId;
  32153. return true;
  32154. }
  32155. return false;
  32156. }
  32157. // other groups are updated just when groupNode.needsUpdate is true
  32158. _chainKeys$2[ 0 ] = groupNode;
  32159. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32160. let groupData = this.groupsData.get( _chainKeys$2 );
  32161. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32162. _chainKeys$2.length = 0;
  32163. if ( groupData.version !== groupNode.version ) {
  32164. groupData.version = groupNode.version;
  32165. return true;
  32166. }
  32167. return false;
  32168. }
  32169. /**
  32170. * Returns the cache key for the given render object.
  32171. *
  32172. * @param {RenderObject} renderObject - The render object.
  32173. * @return {Number} The cache key.
  32174. */
  32175. getForRenderCacheKey( renderObject ) {
  32176. return renderObject.initialCacheKey;
  32177. }
  32178. /**
  32179. * Returns a node builder state for the given render object.
  32180. *
  32181. * @param {RenderObject} renderObject - The render object.
  32182. * @return {NodeBuilderState} The node builder state.
  32183. */
  32184. getForRender( renderObject ) {
  32185. const renderObjectData = this.get( renderObject );
  32186. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32187. if ( nodeBuilderState === undefined ) {
  32188. const { nodeBuilderCache } = this;
  32189. const cacheKey = this.getForRenderCacheKey( renderObject );
  32190. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32191. if ( nodeBuilderState === undefined ) {
  32192. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32193. nodeBuilder.scene = renderObject.scene;
  32194. nodeBuilder.material = renderObject.material;
  32195. nodeBuilder.camera = renderObject.camera;
  32196. nodeBuilder.context.material = renderObject.material;
  32197. nodeBuilder.lightsNode = renderObject.lightsNode;
  32198. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32199. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32200. nodeBuilder.clippingContext = renderObject.clippingContext;
  32201. nodeBuilder.build();
  32202. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32203. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32204. }
  32205. nodeBuilderState.usedTimes ++;
  32206. renderObjectData.nodeBuilderState = nodeBuilderState;
  32207. }
  32208. return nodeBuilderState;
  32209. }
  32210. /**
  32211. * Deletes the given object from the internal data map
  32212. *
  32213. * @param {Any} object - The object to delete.
  32214. * @return {Object?} The deleted dictionary.
  32215. */
  32216. delete( object ) {
  32217. if ( object.isRenderObject ) {
  32218. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32219. nodeBuilderState.usedTimes --;
  32220. if ( nodeBuilderState.usedTimes === 0 ) {
  32221. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32222. }
  32223. }
  32224. return super.delete( object );
  32225. }
  32226. /**
  32227. * Returns a node builder state for the given compute node.
  32228. *
  32229. * @param {Node} computeNode - The compute node.
  32230. * @return {NodeBuilderState} The node builder state.
  32231. */
  32232. getForCompute( computeNode ) {
  32233. const computeData = this.get( computeNode );
  32234. let nodeBuilderState = computeData.nodeBuilderState;
  32235. if ( nodeBuilderState === undefined ) {
  32236. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32237. nodeBuilder.build();
  32238. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32239. computeData.nodeBuilderState = nodeBuilderState;
  32240. }
  32241. return nodeBuilderState;
  32242. }
  32243. /**
  32244. * Creates a node builder state for the given node builder.
  32245. *
  32246. * @private
  32247. * @param {NodeBuilder} nodeBuilder - The node builder.
  32248. * @return {NodeBuilderState} The node builder state.
  32249. */
  32250. _createNodeBuilderState( nodeBuilder ) {
  32251. return new NodeBuilderState(
  32252. nodeBuilder.vertexShader,
  32253. nodeBuilder.fragmentShader,
  32254. nodeBuilder.computeShader,
  32255. nodeBuilder.getAttributesArray(),
  32256. nodeBuilder.getBindings(),
  32257. nodeBuilder.updateNodes,
  32258. nodeBuilder.updateBeforeNodes,
  32259. nodeBuilder.updateAfterNodes,
  32260. nodeBuilder.observer,
  32261. nodeBuilder.transforms
  32262. );
  32263. }
  32264. /**
  32265. * Returns an environment node for the current configured
  32266. * scene environment.
  32267. *
  32268. * @param {Scene} scene - The scene.
  32269. * @return {Node} A node representing the current scene environment.
  32270. */
  32271. getEnvironmentNode( scene ) {
  32272. this.updateEnvironment( scene );
  32273. let environmentNode = null;
  32274. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32275. environmentNode = scene.environmentNode;
  32276. } else {
  32277. const sceneData = this.get( scene );
  32278. if ( sceneData.environmentNode ) {
  32279. environmentNode = sceneData.environmentNode;
  32280. }
  32281. }
  32282. return environmentNode;
  32283. }
  32284. /**
  32285. * Returns a background node for the current configured
  32286. * scene background.
  32287. *
  32288. * @param {Scene} scene - The scene.
  32289. * @return {Node} A node representing the current scene background.
  32290. */
  32291. getBackgroundNode( scene ) {
  32292. this.updateBackground( scene );
  32293. let backgroundNode = null;
  32294. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32295. backgroundNode = scene.backgroundNode;
  32296. } else {
  32297. const sceneData = this.get( scene );
  32298. if ( sceneData.backgroundNode ) {
  32299. backgroundNode = sceneData.backgroundNode;
  32300. }
  32301. }
  32302. return backgroundNode;
  32303. }
  32304. /**
  32305. * Returns a fog node for the current configured scene fog.
  32306. *
  32307. * @param {Scene} scene - The scene.
  32308. * @return {Node} A node representing the current scene fog.
  32309. */
  32310. getFogNode( scene ) {
  32311. this.updateFog( scene );
  32312. return scene.fogNode || this.get( scene ).fogNode || null;
  32313. }
  32314. /**
  32315. * Returns a cache key for the given scene and lights node.
  32316. * This key is used by `RenderObject` as a part of the dynamic
  32317. * cache key (a key that must be checked every time the render
  32318. * objects is drawn).
  32319. *
  32320. * @param {Scene} scene - The scene.
  32321. * @param {LightsNode} lightsNode - The lights node.
  32322. * @return {Number} The cache key.
  32323. */
  32324. getCacheKey( scene, lightsNode ) {
  32325. _chainKeys$2[ 0 ] = scene;
  32326. _chainKeys$2[ 1 ] = lightsNode;
  32327. const callId = this.renderer.info.calls;
  32328. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32329. if ( cacheKeyData.callId !== callId ) {
  32330. const environmentNode = this.getEnvironmentNode( scene );
  32331. const fogNode = this.getFogNode( scene );
  32332. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32333. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32334. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32335. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32336. cacheKeyData.callId = callId;
  32337. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32338. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32339. _cacheKeyValues.length = 0;
  32340. }
  32341. _chainKeys$2.length = 0;
  32342. return cacheKeyData.cacheKey;
  32343. }
  32344. /**
  32345. * A boolean that indicates whether tone mapping should be enabled
  32346. * or not.
  32347. *
  32348. * @type {Boolean}
  32349. */
  32350. get isToneMappingState() {
  32351. return this.renderer.getRenderTarget() ? false : true;
  32352. }
  32353. /**
  32354. * If a scene background is configured, this method makes sure to
  32355. * represent the background with a corresponding node-based implementation.
  32356. *
  32357. * @param {Scene} scene - The scene.
  32358. */
  32359. updateBackground( scene ) {
  32360. const sceneData = this.get( scene );
  32361. const background = scene.background;
  32362. if ( background ) {
  32363. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32364. if ( sceneData.background !== background || forceUpdate ) {
  32365. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32366. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32367. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32368. return pmremTexture( background );
  32369. } else {
  32370. let envMap;
  32371. if ( background.isCubeTexture === true ) {
  32372. envMap = cubeTexture( background );
  32373. } else {
  32374. envMap = texture( background );
  32375. }
  32376. return cubeMapNode( envMap );
  32377. }
  32378. } else if ( background.isTexture === true ) {
  32379. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32380. } else if ( background.isColor !== true ) {
  32381. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32382. }
  32383. }, forceUpdate );
  32384. sceneData.backgroundNode = backgroundNode;
  32385. sceneData.background = background;
  32386. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32387. }
  32388. } else if ( sceneData.backgroundNode ) {
  32389. delete sceneData.backgroundNode;
  32390. delete sceneData.background;
  32391. }
  32392. }
  32393. /**
  32394. * This method is part of the caching of nodes which are used to represents the
  32395. * scene's background, fog or environment.
  32396. *
  32397. * @param {String} type - The type of object to cache.
  32398. * @param {Object} object - The object.
  32399. * @param {Function} callback - A callback that produces a node representation for the given object.
  32400. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32401. * @return {Node} The node representation.
  32402. */
  32403. getCacheNode( type, object, callback, forceUpdate = false ) {
  32404. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32405. let node = nodeCache.get( object );
  32406. if ( node === undefined || forceUpdate ) {
  32407. node = callback();
  32408. nodeCache.set( object, node );
  32409. }
  32410. return node;
  32411. }
  32412. /**
  32413. * If a scene fog is configured, this method makes sure to
  32414. * represent the fog with a corresponding node-based implementation.
  32415. *
  32416. * @param {Scene} scene - The scene.
  32417. */
  32418. updateFog( scene ) {
  32419. const sceneData = this.get( scene );
  32420. const sceneFog = scene.fog;
  32421. if ( sceneFog ) {
  32422. if ( sceneData.fog !== sceneFog ) {
  32423. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32424. if ( sceneFog.isFogExp2 ) {
  32425. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32426. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32427. return fog( color, densityFogFactor( density ) );
  32428. } else if ( sceneFog.isFog ) {
  32429. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32430. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32431. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32432. return fog( color, rangeFogFactor( near, far ) );
  32433. } else {
  32434. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32435. }
  32436. } );
  32437. sceneData.fogNode = fogNode;
  32438. sceneData.fog = sceneFog;
  32439. }
  32440. } else {
  32441. delete sceneData.fogNode;
  32442. delete sceneData.fog;
  32443. }
  32444. }
  32445. /**
  32446. * If a scene environment is configured, this method makes sure to
  32447. * represent the environment with a corresponding node-based implementation.
  32448. *
  32449. * @param {Scene} scene - The scene.
  32450. */
  32451. updateEnvironment( scene ) {
  32452. const sceneData = this.get( scene );
  32453. const environment = scene.environment;
  32454. if ( environment ) {
  32455. if ( sceneData.environment !== environment ) {
  32456. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32457. if ( environment.isCubeTexture === true ) {
  32458. return cubeTexture( environment );
  32459. } else if ( environment.isTexture === true ) {
  32460. return texture( environment );
  32461. } else {
  32462. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32463. }
  32464. } );
  32465. sceneData.environmentNode = environmentNode;
  32466. sceneData.environment = environment;
  32467. }
  32468. } else if ( sceneData.environmentNode ) {
  32469. delete sceneData.environmentNode;
  32470. delete sceneData.environment;
  32471. }
  32472. }
  32473. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32474. const nodeFrame = this.nodeFrame;
  32475. nodeFrame.renderer = renderer;
  32476. nodeFrame.scene = scene;
  32477. nodeFrame.object = object;
  32478. nodeFrame.camera = camera;
  32479. nodeFrame.material = material;
  32480. return nodeFrame;
  32481. }
  32482. getNodeFrameForRender( renderObject ) {
  32483. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32484. }
  32485. /**
  32486. * Returns the current output cache key.
  32487. *
  32488. * @return {String} The output cache key.
  32489. */
  32490. getOutputCacheKey() {
  32491. const renderer = this.renderer;
  32492. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32493. }
  32494. /**
  32495. * Checks if the output configuration (tone mapping and color space) for
  32496. * the given target has changed.
  32497. *
  32498. * @param {Texture} outputTarget - The output target.
  32499. * @return {Boolean} Whether the output configuration has changed or not.
  32500. */
  32501. hasOutputChange( outputTarget ) {
  32502. const cacheKey = _outputNodeMap.get( outputTarget );
  32503. return cacheKey !== this.getOutputCacheKey();
  32504. }
  32505. /**
  32506. * Returns a node that represents the output configuration (tone mapping and
  32507. * color space) for the current target.
  32508. *
  32509. * @param {Texture} outputTarget - The output target.
  32510. * @return {Node} The output node.
  32511. */
  32512. getOutputNode( outputTarget ) {
  32513. const renderer = this.renderer;
  32514. const cacheKey = this.getOutputCacheKey();
  32515. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32516. _outputNodeMap.set( outputTarget, cacheKey );
  32517. return output;
  32518. }
  32519. /**
  32520. * Triggers the call of `updateBefore()` methods
  32521. * for all nodes of the given render object.
  32522. *
  32523. * @param {RenderObject} renderObject - The render object.
  32524. */
  32525. updateBefore( renderObject ) {
  32526. const nodeBuilder = renderObject.getNodeBuilderState();
  32527. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32528. // update frame state for each node
  32529. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32530. }
  32531. }
  32532. /**
  32533. * Triggers the call of `updateAfter()` methods
  32534. * for all nodes of the given render object.
  32535. *
  32536. * @param {RenderObject} renderObject - The render object.
  32537. */
  32538. updateAfter( renderObject ) {
  32539. const nodeBuilder = renderObject.getNodeBuilderState();
  32540. for ( const node of nodeBuilder.updateAfterNodes ) {
  32541. // update frame state for each node
  32542. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32543. }
  32544. }
  32545. /**
  32546. * Triggers the call of `update()` methods
  32547. * for all nodes of the given compute node.
  32548. *
  32549. * @param {Node} computeNode - The compute node.
  32550. */
  32551. updateForCompute( computeNode ) {
  32552. const nodeFrame = this.getNodeFrame();
  32553. const nodeBuilder = this.getForCompute( computeNode );
  32554. for ( const node of nodeBuilder.updateNodes ) {
  32555. nodeFrame.updateNode( node );
  32556. }
  32557. }
  32558. /**
  32559. * Triggers the call of `update()` methods
  32560. * for all nodes of the given compute node.
  32561. *
  32562. * @param {RenderObject} renderObject - The render object.
  32563. */
  32564. updateForRender( renderObject ) {
  32565. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32566. const nodeBuilder = renderObject.getNodeBuilderState();
  32567. for ( const node of nodeBuilder.updateNodes ) {
  32568. nodeFrame.updateNode( node );
  32569. }
  32570. }
  32571. /**
  32572. * Returns `true` if the given render object requires a refresh.
  32573. *
  32574. * @param {RenderObject} renderObject - The render object.
  32575. * @return {Boolean} Whether the given render object requires a refresh or not.
  32576. */
  32577. needsRefresh( renderObject ) {
  32578. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32579. const monitor = renderObject.getMonitor();
  32580. return monitor.needsRefresh( renderObject, nodeFrame );
  32581. }
  32582. /**
  32583. * Frees the internal resources.
  32584. */
  32585. dispose() {
  32586. super.dispose();
  32587. this.nodeFrame = new NodeFrame();
  32588. this.nodeBuilderCache = new Map();
  32589. this.cacheLib = {};
  32590. }
  32591. }
  32592. const _plane = /*@__PURE__*/ new Plane();
  32593. /**
  32594. * Represents the state that is used to perform clipping via clipping planes.
  32595. * There is a default clipping context for each render context. When the
  32596. * scene holds instances of `ClippingGroup`, there will be a context for each
  32597. * group.
  32598. *
  32599. * @private
  32600. */
  32601. class ClippingContext {
  32602. /**
  32603. * Constructs a new clipping context.
  32604. *
  32605. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32606. */
  32607. constructor( parentContext = null ) {
  32608. /**
  32609. * The clipping context's version.
  32610. *
  32611. * @type {Number}
  32612. * @readonly
  32613. */
  32614. this.version = 0;
  32615. /**
  32616. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32617. *
  32618. * @type {Boolean?}
  32619. * @default null
  32620. */
  32621. this.clipIntersection = null;
  32622. /**
  32623. * The clipping context's cache key.
  32624. *
  32625. * @type {String}
  32626. */
  32627. this.cacheKey = '';
  32628. /**
  32629. * Whether the shadow pass is active or not.
  32630. *
  32631. * @type {Boolean}
  32632. * @default false
  32633. */
  32634. this.shadowPass = false;
  32635. /**
  32636. * The view normal matrix.
  32637. *
  32638. * @type {Matrix3}
  32639. */
  32640. this.viewNormalMatrix = new Matrix3();
  32641. /**
  32642. * Internal cache for maintaining clipping contexts.
  32643. *
  32644. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32645. */
  32646. this.clippingGroupContexts = new WeakMap();
  32647. /**
  32648. * The intersection planes.
  32649. *
  32650. * @type {Array<Vector4>}
  32651. */
  32652. this.intersectionPlanes = [];
  32653. /**
  32654. * The intersection planes.
  32655. *
  32656. * @type {Array<Vector4>}
  32657. */
  32658. this.unionPlanes = [];
  32659. /**
  32660. * The version of the clipping context's parent context.
  32661. *
  32662. * @type {Number?}
  32663. * @readonly
  32664. */
  32665. this.parentVersion = null;
  32666. if ( parentContext !== null ) {
  32667. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32668. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32669. this.shadowPass = parentContext.shadowPass;
  32670. this.viewMatrix = parentContext.viewMatrix;
  32671. }
  32672. }
  32673. /**
  32674. * Projects the given source clipping planes and writes the result into the
  32675. * destination array.
  32676. *
  32677. * @param {Array<Plane>} source - The source clipping planes.
  32678. * @param {Array<Vector4>} destination - The destination.
  32679. * @param {Number} offset - The offset.
  32680. */
  32681. projectPlanes( source, destination, offset ) {
  32682. const l = source.length;
  32683. for ( let i = 0; i < l; i ++ ) {
  32684. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32685. const v = destination[ offset + i ];
  32686. const normal = _plane.normal;
  32687. v.x = - normal.x;
  32688. v.y = - normal.y;
  32689. v.z = - normal.z;
  32690. v.w = _plane.constant;
  32691. }
  32692. }
  32693. /**
  32694. * Updates the root clipping context of a scene.
  32695. *
  32696. * @param {Scene} scene - The scene.
  32697. * @param {Camera} camera - The camera that is used to render the scene.
  32698. */
  32699. updateGlobal( scene, camera ) {
  32700. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32701. this.viewMatrix = camera.matrixWorldInverse;
  32702. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32703. }
  32704. /**
  32705. * Updates the clipping context.
  32706. *
  32707. * @param {ClippingContext} parentContext - The parent context.
  32708. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32709. */
  32710. update( parentContext, clippingGroup ) {
  32711. let update = false;
  32712. if ( parentContext.version !== this.parentVersion ) {
  32713. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32714. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32715. this.parentVersion = parentContext.version;
  32716. }
  32717. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32718. this.clipIntersection = clippingGroup.clipIntersection;
  32719. if ( this.clipIntersection ) {
  32720. this.unionPlanes.length = parentContext.unionPlanes.length;
  32721. } else {
  32722. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32723. }
  32724. }
  32725. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32726. const l = srcClippingPlanes.length;
  32727. let dstClippingPlanes;
  32728. let offset;
  32729. if ( this.clipIntersection ) {
  32730. dstClippingPlanes = this.intersectionPlanes;
  32731. offset = parentContext.intersectionPlanes.length;
  32732. } else {
  32733. dstClippingPlanes = this.unionPlanes;
  32734. offset = parentContext.unionPlanes.length;
  32735. }
  32736. if ( dstClippingPlanes.length !== offset + l ) {
  32737. dstClippingPlanes.length = offset + l;
  32738. for ( let i = 0; i < l; i ++ ) {
  32739. dstClippingPlanes[ offset + i ] = new Vector4();
  32740. }
  32741. update = true;
  32742. }
  32743. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32744. if ( update ) {
  32745. this.version ++;
  32746. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32747. }
  32748. }
  32749. /**
  32750. * Returns a clipping context for the given clipping group.
  32751. *
  32752. * @param {ClippingGroup} clippingGroup - The clipping group.
  32753. * @return {ClippingContext} The clipping context.
  32754. */
  32755. getGroupContext( clippingGroup ) {
  32756. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32757. let context = this.clippingGroupContexts.get( clippingGroup );
  32758. if ( context === undefined ) {
  32759. context = new ClippingContext( this );
  32760. this.clippingGroupContexts.set( clippingGroup, context );
  32761. }
  32762. context.update( this, clippingGroup );
  32763. return context;
  32764. }
  32765. /**
  32766. * The count of union clipping planes.
  32767. *
  32768. * @type {Number}
  32769. * @readonly
  32770. */
  32771. get unionClippingCount() {
  32772. return this.unionPlanes.length;
  32773. }
  32774. }
  32775. /**
  32776. * This module is used to represent render bundles inside the renderer
  32777. * for further processing.
  32778. *
  32779. * @private
  32780. */
  32781. class RenderBundle {
  32782. /**
  32783. * Constructs a new bundle group.
  32784. *
  32785. * @param {BundleGroup} bundleGroup - The bundle group.
  32786. * @param {Camera} camera - The camera the bundle group is rendered with.
  32787. */
  32788. constructor( bundleGroup, camera ) {
  32789. this.bundleGroup = bundleGroup;
  32790. this.camera = camera;
  32791. }
  32792. }
  32793. const _chainKeys$1 = [];
  32794. /**
  32795. * This renderer module manages render bundles.
  32796. *
  32797. * @private
  32798. */
  32799. class RenderBundles {
  32800. /**
  32801. * Constructs a new render bundle management component.
  32802. */
  32803. constructor() {
  32804. /**
  32805. * A chain map for maintaining the render bundles.
  32806. *
  32807. * @type {ChainMap}
  32808. */
  32809. this.bundles = new ChainMap();
  32810. }
  32811. /**
  32812. * Returns a render bundle for the given bundle group and camera.
  32813. *
  32814. * @param {BundleGroup} bundleGroup - The bundle group.
  32815. * @param {Camera} camera - The camera the bundle group is rendered with.
  32816. * @return {RenderBundle} The render bundle.
  32817. */
  32818. get( bundleGroup, camera ) {
  32819. const bundles = this.bundles;
  32820. _chainKeys$1[ 0 ] = bundleGroup;
  32821. _chainKeys$1[ 1 ] = camera;
  32822. let bundle = bundles.get( _chainKeys$1 );
  32823. if ( bundle === undefined ) {
  32824. bundle = new RenderBundle( bundleGroup, camera );
  32825. bundles.set( _chainKeys$1, bundle );
  32826. }
  32827. _chainKeys$1.length = 0;
  32828. return bundle;
  32829. }
  32830. /**
  32831. * Frees all internal resources.
  32832. */
  32833. dispose() {
  32834. this.bundles = new ChainMap();
  32835. }
  32836. }
  32837. /**
  32838. * The purpose of a node library is to assign node implementations
  32839. * to existing library features. In `WebGPURenderer` lights, materials
  32840. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32841. * are implemented with node-based modules.
  32842. *
  32843. * @private
  32844. */
  32845. class NodeLibrary {
  32846. /**
  32847. * Constructs a new node library.
  32848. */
  32849. constructor() {
  32850. /**
  32851. * A weak map that maps lights to light nodes.
  32852. *
  32853. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32854. */
  32855. this.lightNodes = new WeakMap();
  32856. /**
  32857. * A map that maps materials to node materials.
  32858. *
  32859. * @type {Map<String,NodeMaterial.constructor>}
  32860. */
  32861. this.materialNodes = new Map();
  32862. /**
  32863. * A map that maps tone mapping techniques (constants)
  32864. * to tone mapping node functions.
  32865. *
  32866. * @type {Map<Number,Function>}
  32867. */
  32868. this.toneMappingNodes = new Map();
  32869. }
  32870. /**
  32871. * Returns a matching node material instance for the given material object.
  32872. *
  32873. * This method also assigns/copies the properties of the given material object
  32874. * to the node material. This is done to make sure the current material
  32875. * configuration carries over to the node version.
  32876. *
  32877. * @param {Material} material - A material.
  32878. * @return {NodeMaterial} The corresponding node material.
  32879. */
  32880. fromMaterial( material ) {
  32881. if ( material.isNodeMaterial ) return material;
  32882. let nodeMaterial = null;
  32883. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32884. if ( nodeMaterialClass !== null ) {
  32885. nodeMaterial = new nodeMaterialClass();
  32886. for ( const key in material ) {
  32887. nodeMaterial[ key ] = material[ key ];
  32888. }
  32889. }
  32890. return nodeMaterial;
  32891. }
  32892. /**
  32893. * Adds a tone mapping node function for a tone mapping technique (constant).
  32894. *
  32895. * @param {Function} toneMappingNode - The tone mapping node function.
  32896. * @param {Number} toneMapping - The tone mapping.
  32897. */
  32898. addToneMapping( toneMappingNode, toneMapping ) {
  32899. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32900. }
  32901. /**
  32902. * Returns a tone mapping node function for a tone mapping technique (constant).
  32903. *
  32904. * @param {Number} toneMapping - The tone mapping.
  32905. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32906. */
  32907. getToneMappingFunction( toneMapping ) {
  32908. return this.toneMappingNodes.get( toneMapping ) || null;
  32909. }
  32910. /**
  32911. * Returns a node material class definition for a material type.
  32912. *
  32913. * @param {String} materialType - The material type.
  32914. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32915. */
  32916. getMaterialNodeClass( materialType ) {
  32917. return this.materialNodes.get( materialType ) || null;
  32918. }
  32919. /**
  32920. * Adds a node material class definition for a given material type.
  32921. *
  32922. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32923. * @param {String} materialClassType - The material type.
  32924. */
  32925. addMaterial( materialNodeClass, materialClassType ) {
  32926. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32927. }
  32928. /**
  32929. * Returns a light node class definition for a light class definition.
  32930. *
  32931. * @param {Light.constructor} light - The light class definition.
  32932. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32933. */
  32934. getLightNodeClass( light ) {
  32935. return this.lightNodes.get( light ) || null;
  32936. }
  32937. /**
  32938. * Adds a light node class definition for a given light class definition.
  32939. *
  32940. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32941. * @param {Light.constructor} lightClass - The light class definition.
  32942. */
  32943. addLight( lightNodeClass, lightClass ) {
  32944. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32945. }
  32946. /**
  32947. * Adds a node class definition for the given type to the provided type library.
  32948. *
  32949. * @param {Any} nodeClass - The node class definition.
  32950. * @param {Number|String} type - The object type.
  32951. * @param {Map} library - The type library.
  32952. */
  32953. addType( nodeClass, type, library ) {
  32954. if ( library.has( type ) ) {
  32955. console.warn( `Redefinition of node ${ type }` );
  32956. return;
  32957. }
  32958. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32959. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32960. library.set( type, nodeClass );
  32961. }
  32962. /**
  32963. * Adds a node class definition for the given class definition to the provided type library.
  32964. *
  32965. * @param {Any} nodeClass - The node class definition.
  32966. * @param {Any} baseClass - The class definition.
  32967. * @param {WeakMap} library - The type library.
  32968. */
  32969. addClass( nodeClass, baseClass, library ) {
  32970. if ( library.has( baseClass ) ) {
  32971. console.warn( `Redefinition of node ${ baseClass.name }` );
  32972. return;
  32973. }
  32974. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32975. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32976. library.set( baseClass, nodeClass );
  32977. }
  32978. }
  32979. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32980. const _chainKeys = [];
  32981. /**
  32982. * This renderer module manages the lights nodes which are unique
  32983. * per scene and camera combination.
  32984. *
  32985. * The lights node itself is later configured in the render list
  32986. * with the actual lights from the scene.
  32987. *
  32988. * @private
  32989. * @augments ChainMap
  32990. */
  32991. class Lighting extends ChainMap {
  32992. /**
  32993. * Constructs a lighting management component.
  32994. */
  32995. constructor() {
  32996. super();
  32997. }
  32998. /**
  32999. * Creates a new lights node for the given array of lights.
  33000. *
  33001. * @param {Array<Light>} lights - The render object.
  33002. * @return {LightsNode} The lights node.
  33003. */
  33004. createNode( lights = [] ) {
  33005. return new LightsNode().setLights( lights );
  33006. }
  33007. /**
  33008. * Returns a lights node for the given scene and camera.
  33009. *
  33010. * @param {Scene} scene - The scene.
  33011. * @param {Camera} camera - The camera.
  33012. * @return {LightsNode} The lights node.
  33013. */
  33014. getNode( scene, camera ) {
  33015. // ignore post-processing
  33016. if ( scene.isQuadMesh ) return _defaultLights;
  33017. _chainKeys[ 0 ] = scene;
  33018. _chainKeys[ 1 ] = camera;
  33019. let node = this.get( _chainKeys );
  33020. if ( node === undefined ) {
  33021. node = this.createNode();
  33022. this.set( _chainKeys, node );
  33023. }
  33024. _chainKeys.length = 0;
  33025. return node;
  33026. }
  33027. }
  33028. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33029. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33030. /**
  33031. * The XR manager is built on top of the WebXR Device API to
  33032. * manage XR sessions with `WebGPURenderer`.
  33033. *
  33034. * XR is currently only supported with a WebGL 2 backend.
  33035. *
  33036. * @augments EventDispatcher
  33037. */
  33038. class XRManager extends EventDispatcher {
  33039. /**
  33040. * Constructs a new XR manager.
  33041. *
  33042. * @param {Renderer} renderer - The renderer.
  33043. */
  33044. constructor( renderer ) {
  33045. super();
  33046. /**
  33047. * This flag globally enables XR rendering.
  33048. *
  33049. * @type {Boolean}
  33050. * @default false
  33051. */
  33052. this.enabled = false;
  33053. /**
  33054. * Whether the XR device is currently presenting or not.
  33055. *
  33056. * @type {Boolean}
  33057. * @default false
  33058. * @readonly
  33059. */
  33060. this.isPresenting = false;
  33061. /**
  33062. * Whether the XR camera should automatically be updated or not.
  33063. *
  33064. * @type {Boolean}
  33065. * @default true
  33066. */
  33067. this.cameraAutoUpdate = true;
  33068. /**
  33069. * The renderer.
  33070. *
  33071. * @private
  33072. * @type {Renderer}
  33073. */
  33074. this._renderer = renderer;
  33075. // camera
  33076. /**
  33077. * Represents the camera for the left eye.
  33078. *
  33079. * @private
  33080. * @type {PerspectiveCamera}
  33081. */
  33082. this._cameraL = new PerspectiveCamera();
  33083. this._cameraL.viewport = new Vector4();
  33084. /**
  33085. * Represents the camera for the right eye.
  33086. *
  33087. * @private
  33088. * @type {PerspectiveCamera}
  33089. */
  33090. this._cameraR = new PerspectiveCamera();
  33091. this._cameraR.viewport = new Vector4();
  33092. /**
  33093. * A list of cameras used for rendering the XR views.
  33094. *
  33095. * @private
  33096. * @type {Array<Camera>}
  33097. */
  33098. this._cameras = [ this._cameraL, this._cameraR ];
  33099. /**
  33100. * The main XR camera.
  33101. *
  33102. * @private
  33103. * @type {ArrayCamera}
  33104. */
  33105. this._cameraXR = new ArrayCamera();
  33106. /**
  33107. * The current near value of the XR camera.
  33108. *
  33109. * @private
  33110. * @type {Number?}
  33111. * @default null
  33112. */
  33113. this._currentDepthNear = null;
  33114. /**
  33115. * The current far value of the XR camera.
  33116. *
  33117. * @private
  33118. * @type {Number?}
  33119. * @default null
  33120. */
  33121. this._currentDepthFar = null;
  33122. /**
  33123. * A list of WebXR controllers requested by the application.
  33124. *
  33125. * @private
  33126. * @type {Array<WebXRController>}
  33127. */
  33128. this._controllers = [];
  33129. /**
  33130. * A list of XR input source. Each input source belongs to
  33131. * an instance of WebXRController.
  33132. *
  33133. * @private
  33134. * @type {Array<XRInputSource?>}
  33135. */
  33136. this._controllerInputSources = [];
  33137. /**
  33138. * The current render target of the renderer.
  33139. *
  33140. * @private
  33141. * @type {RenderTarget?}
  33142. * @default null
  33143. */
  33144. this._currentRenderTarget = null;
  33145. /**
  33146. * The XR render target that represents the rendering destination
  33147. * during an active XR session.
  33148. *
  33149. * @private
  33150. * @type {RenderTarget?}
  33151. * @default null
  33152. */
  33153. this._xrRenderTarget = null;
  33154. /**
  33155. * The current animation context.
  33156. *
  33157. * @private
  33158. * @type {Window?}
  33159. * @default null
  33160. */
  33161. this._currentAnimationContext = null;
  33162. /**
  33163. * The current animation loop.
  33164. *
  33165. * @private
  33166. * @type {Function?}
  33167. * @default null
  33168. */
  33169. this._currentAnimationLoop = null;
  33170. /**
  33171. * The current pixel ratio.
  33172. *
  33173. * @private
  33174. * @type {Number?}
  33175. * @default null
  33176. */
  33177. this._currentPixelRatio = null;
  33178. /**
  33179. * The current size of the renderer's canvas
  33180. * in logical pixel unit.
  33181. *
  33182. * @private
  33183. * @type {Vector2}
  33184. */
  33185. this._currentSize = new Vector2();
  33186. /**
  33187. * The default event listener for handling events inside a XR session.
  33188. *
  33189. * @private
  33190. * @type {Function}
  33191. */
  33192. this._onSessionEvent = onSessionEvent.bind( this );
  33193. /**
  33194. * The event listener for handling the end of a XR session.
  33195. *
  33196. * @private
  33197. * @type {Function}
  33198. */
  33199. this._onSessionEnd = onSessionEnd.bind( this );
  33200. /**
  33201. * The event listener for handling the `inputsourceschange` event.
  33202. *
  33203. * @private
  33204. * @type {Function}
  33205. */
  33206. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33207. /**
  33208. * The animation loop which is used as a replacement for the default
  33209. * animation loop of the applicatio. It is only used when a XR session
  33210. * is active.
  33211. *
  33212. * @private
  33213. * @type {Function}
  33214. */
  33215. this._onAnimationFrame = onAnimationFrame.bind( this );
  33216. /**
  33217. * The current XR reference space.
  33218. *
  33219. * @private
  33220. * @type {XRReferenceSpace?}
  33221. * @default null
  33222. */
  33223. this._referenceSpace = null;
  33224. /**
  33225. * The current XR reference space type.
  33226. *
  33227. * @private
  33228. * @type {String}
  33229. * @default 'local-floor'
  33230. */
  33231. this._referenceSpaceType = 'local-floor';
  33232. /**
  33233. * A custom reference space defined by the application.
  33234. *
  33235. * @private
  33236. * @type {XRReferenceSpace?}
  33237. * @default null
  33238. */
  33239. this._customReferenceSpace = null;
  33240. /**
  33241. * The framebuffer scale factor.
  33242. *
  33243. * @private
  33244. * @type {Number}
  33245. * @default 1
  33246. */
  33247. this._framebufferScaleFactor = 1;
  33248. /**
  33249. * The foveation factor.
  33250. *
  33251. * @private
  33252. * @type {Number}
  33253. * @default 1
  33254. */
  33255. this._foveation = 1.0;
  33256. /**
  33257. * A reference to the current XR session.
  33258. *
  33259. * @private
  33260. * @type {XRSession?}
  33261. * @default null
  33262. */
  33263. this._session = null;
  33264. /**
  33265. * A reference to the current XR base layer.
  33266. *
  33267. * @private
  33268. * @type {XRWebGLLayer?}
  33269. * @default null
  33270. */
  33271. this._glBaseLayer = null;
  33272. /**
  33273. * A reference to the current XR frame.
  33274. *
  33275. * @private
  33276. * @type {XRFrame?}
  33277. * @default null
  33278. */
  33279. this._xrFrame = null;
  33280. }
  33281. /**
  33282. * Returns an instance of `THREE.Group` that represents the transformation
  33283. * of a XR controller in target ray space. The requested controller is defined
  33284. * by the given index.
  33285. *
  33286. * @param {Number} index - The index of the XR controller.
  33287. * @return {Group} A group that represents the controller's transformation.
  33288. */
  33289. getController( index ) {
  33290. const controller = this._getController( index );
  33291. return controller.getTargetRaySpace();
  33292. }
  33293. /**
  33294. * Returns an instance of `THREE.Group` that represents the transformation
  33295. * of a XR controller in grip space. The requested controller is defined
  33296. * by the given index.
  33297. *
  33298. * @param {Number} index - The index of the XR controller.
  33299. * @return {Group} A group that represents the controller's transformation.
  33300. */
  33301. getControllerGrip( index ) {
  33302. const controller = this._getController( index );
  33303. return controller.getGripSpace();
  33304. }
  33305. /**
  33306. * Returns an instance of `THREE.Group` that represents the transformation
  33307. * of a XR controller in hand space. The requested controller is defined
  33308. * by the given index.
  33309. *
  33310. * @param {Number} index - The index of the XR controller.
  33311. * @return {Group} A group that represents the controller's transformation.
  33312. */
  33313. getHand( index ) {
  33314. const controller = this._getController( index );
  33315. return controller.getHandSpace();
  33316. }
  33317. /**
  33318. * Returns the foveation value.
  33319. *
  33320. * @return {Number|undefined} The foveation value. Returns `undefined` if no base layer is defined.
  33321. */
  33322. getFoveation() {
  33323. if ( this._glBaseLayer === null ) {
  33324. return undefined;
  33325. }
  33326. return this._foveation;
  33327. }
  33328. /**
  33329. * Sets the foveation value.
  33330. *
  33331. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33332. * and `1` means maximum foveation (the edges render at lower resolution).
  33333. */
  33334. setFoveation( foveation ) {
  33335. this._foveation = foveation;
  33336. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33337. this._glBaseLayer.fixedFoveation = foveation;
  33338. }
  33339. }
  33340. /**
  33341. * Returns the framebuffer scale factor.
  33342. *
  33343. * @return {Number} The framebuffer scale factor.
  33344. */
  33345. getFramebufferScaleFactor() {
  33346. return this._framebufferScaleFactor;
  33347. }
  33348. /**
  33349. * Sets the framebuffer scale factor.
  33350. *
  33351. * This method can not be used during a XR session.
  33352. *
  33353. * @param {Number} factor - The framebuffer scale factor.
  33354. */
  33355. setFramebufferScaleFactor( factor ) {
  33356. this._framebufferScaleFactor = factor;
  33357. if ( this.isPresenting === true ) {
  33358. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33359. }
  33360. }
  33361. /**
  33362. * Returns the reference space type.
  33363. *
  33364. * @return {String} The reference space type.
  33365. */
  33366. getReferenceSpaceType() {
  33367. return this._referenceSpaceType;
  33368. }
  33369. /**
  33370. * Sets the reference space type.
  33371. *
  33372. * This method can not be used during a XR session.
  33373. *
  33374. * @param {String} type - The reference space type.
  33375. */
  33376. setReferenceSpaceType( type ) {
  33377. this._referenceSpaceType = type;
  33378. if ( this.isPresenting === true ) {
  33379. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33380. }
  33381. }
  33382. /**
  33383. * Returns the XR reference space.
  33384. *
  33385. * @return {XRReferenceSpace} The XR reference space.
  33386. */
  33387. getReferenceSpace() {
  33388. return this._customReferenceSpace || this._referenceSpace;
  33389. }
  33390. /**
  33391. * Sets a custom XR reference space.
  33392. *
  33393. * @param {XRReferenceSpace} space - The XR reference space.
  33394. */
  33395. setReferenceSpace( space ) {
  33396. this._customReferenceSpace = space;
  33397. }
  33398. /**
  33399. * Returns the XR camera.
  33400. *
  33401. * @return {ArrayCamera} The XR camera.
  33402. */
  33403. getCamera() {
  33404. return this._cameraXR;
  33405. }
  33406. /**
  33407. * Returns the environment blend mode from the current XR session.
  33408. *
  33409. * @return {('opaque'|'additive'|'alpha-blend')?} The environment blend mode. Returns `null` when used outside of a XR session.
  33410. */
  33411. getEnvironmentBlendMode() {
  33412. if ( this._session !== null ) {
  33413. return this._session.environmentBlendMode;
  33414. }
  33415. }
  33416. /**
  33417. * Returns the current XR frame.
  33418. *
  33419. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  33420. */
  33421. getFrame() {
  33422. return this._xrFrame;
  33423. }
  33424. /**
  33425. * Returns the current XR session.
  33426. *
  33427. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  33428. */
  33429. getSession() {
  33430. return this._session;
  33431. }
  33432. /**
  33433. * After a XR session has been requested usually with one of the `*Button` modules, it
  33434. * is injected into the renderer with this method. This method triggers the start of
  33435. * the actual XR rendering.
  33436. *
  33437. * @async
  33438. * @param {XRSession} session - The XR session to set.
  33439. * @return {Promise} A Promise that resolves when the session has been set.
  33440. */
  33441. async setSession( session ) {
  33442. const renderer = this._renderer;
  33443. const gl = renderer.getContext();
  33444. this._session = session;
  33445. if ( session !== null ) {
  33446. if ( renderer.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.' );
  33447. this._currentRenderTarget = renderer.getRenderTarget();
  33448. session.addEventListener( 'select', this._onSessionEvent );
  33449. session.addEventListener( 'selectstart', this._onSessionEvent );
  33450. session.addEventListener( 'selectend', this._onSessionEvent );
  33451. session.addEventListener( 'squeeze', this._onSessionEvent );
  33452. session.addEventListener( 'squeezestart', this._onSessionEvent );
  33453. session.addEventListener( 'squeezeend', this._onSessionEvent );
  33454. session.addEventListener( 'end', this._onSessionEnd );
  33455. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33456. await renderer.makeXRCompatible();
  33457. this._currentPixelRatio = renderer.getPixelRatio();
  33458. renderer.getSize( this._currentSize );
  33459. this._currentAnimationContext = renderer._animation.getContext();
  33460. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  33461. renderer._animation.stop();
  33462. const attributes = gl.getContextAttributes();
  33463. const layerInit = {
  33464. antialias: attributes.antialias,
  33465. alpha: true,
  33466. depth: attributes.depth,
  33467. stencil: attributes.stencil,
  33468. framebufferScaleFactor: this.getFramebufferScaleFactor()
  33469. };
  33470. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  33471. this._glBaseLayer = glBaseLayer;
  33472. session.updateRenderState( { baseLayer: glBaseLayer } );
  33473. renderer.setPixelRatio( 1 );
  33474. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  33475. this._xrRenderTarget = new RenderTarget(
  33476. glBaseLayer.framebufferWidth,
  33477. glBaseLayer.framebufferHeight,
  33478. {
  33479. format: RGBAFormat,
  33480. type: UnsignedByteType,
  33481. colorSpace: renderer.outputColorSpace,
  33482. stencilBuffer: attributes.stencil
  33483. }
  33484. );
  33485. this._xrRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  33486. this.setFoveation( this.getFoveation() );
  33487. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  33488. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  33489. renderer._animation.setContext( session );
  33490. renderer._animation.start();
  33491. this.isPresenting = true;
  33492. this.dispatchEvent( { type: 'sessionstart' } );
  33493. }
  33494. }
  33495. /**
  33496. * This method is called by the renderer per frame and updates the XR camera
  33497. * and it sub cameras based on the given camera. The given camera is the "user"
  33498. * camera created on application level and used for non-XR rendering.
  33499. *
  33500. * @param {PerspectiveCamera} camera - The camera.
  33501. */
  33502. updateCamera( camera ) {
  33503. const session = this._session;
  33504. if ( session === null ) return;
  33505. const depthNear = camera.near;
  33506. const depthFar = camera.far;
  33507. const cameraXR = this._cameraXR;
  33508. const cameraL = this._cameraL;
  33509. const cameraR = this._cameraR;
  33510. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  33511. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  33512. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  33513. // Note that the new renderState won't apply until the next frame. See #18320
  33514. session.updateRenderState( {
  33515. depthNear: cameraXR.near,
  33516. depthFar: cameraXR.far
  33517. } );
  33518. this._currentDepthNear = cameraXR.near;
  33519. this._currentDepthFar = cameraXR.far;
  33520. }
  33521. cameraL.layers.mask = camera.layers.mask | 0b010;
  33522. cameraR.layers.mask = camera.layers.mask | 0b100;
  33523. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  33524. const parent = camera.parent;
  33525. const cameras = cameraXR.cameras;
  33526. updateCamera( cameraXR, parent );
  33527. for ( let i = 0; i < cameras.length; i ++ ) {
  33528. updateCamera( cameras[ i ], parent );
  33529. }
  33530. // update projection matrix for proper view frustum culling
  33531. if ( cameras.length === 2 ) {
  33532. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  33533. } else {
  33534. // assume single camera setup (AR)
  33535. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  33536. }
  33537. // update user camera and its children
  33538. updateUserCamera( camera, cameraXR, parent );
  33539. }
  33540. /**
  33541. * Returns a WebXR controller for the given controller index.
  33542. *
  33543. * @private
  33544. * @param {Number} index - The controller index.
  33545. * @return {WebXRController} The XR controller.
  33546. */
  33547. _getController( index ) {
  33548. let controller = this._controllers[ index ];
  33549. if ( controller === undefined ) {
  33550. controller = new WebXRController();
  33551. this._controllers[ index ] = controller;
  33552. }
  33553. return controller;
  33554. }
  33555. }
  33556. /**
  33557. * Assumes 2 cameras that are parallel and share an X-axis, and that
  33558. * the cameras' projection and world matrices have already been set.
  33559. * And that near and far planes are identical for both cameras.
  33560. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  33561. *
  33562. * @param {ArrayCamera} camera - The camera to update.
  33563. * @param {PerspectiveCamera} cameraL - The left camera.
  33564. * @param {PerspectiveCamera} cameraR - The right camera.
  33565. */
  33566. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  33567. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  33568. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  33569. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  33570. const projL = cameraL.projectionMatrix.elements;
  33571. const projR = cameraR.projectionMatrix.elements;
  33572. // VR systems will have identical far and near planes, and
  33573. // most likely identical top and bottom frustum extents.
  33574. // Use the left camera for these values.
  33575. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  33576. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  33577. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  33578. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  33579. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  33580. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  33581. const left = near * leftFov;
  33582. const right = near * rightFov;
  33583. // Calculate the new camera's position offset from the
  33584. // left camera. xOffset should be roughly half `ipd`.
  33585. const zOffset = ipd / ( - leftFov + rightFov );
  33586. const xOffset = zOffset * - leftFov;
  33587. // TODO: Better way to apply this offset?
  33588. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  33589. camera.translateX( xOffset );
  33590. camera.translateZ( zOffset );
  33591. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  33592. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33593. // Check if the projection uses an infinite far plane.
  33594. if ( projL[ 10 ] === - 1.0 ) {
  33595. // Use the projection matrix from the left eye.
  33596. // The camera offset is sufficient to include the view volumes
  33597. // of both eyes (assuming symmetric projections).
  33598. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  33599. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  33600. } else {
  33601. // Find the union of the frustum values of the cameras and scale
  33602. // the values so that the near plane's position does not change in world space,
  33603. // although must now be relative to the new union camera.
  33604. const near2 = near + zOffset;
  33605. const far2 = far + zOffset;
  33606. const left2 = left - xOffset;
  33607. const right2 = right + ( ipd - xOffset );
  33608. const top2 = topFov * far / far2 * near2;
  33609. const bottom2 = bottomFov * far / far2 * near2;
  33610. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  33611. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33612. }
  33613. }
  33614. /**
  33615. * Updates the world matrices for the given camera based on the parent 3D object.
  33616. *
  33617. * @inner
  33618. * @param {Camera} camera - The camera to update.
  33619. * @param {Object3D} parent - The parent 3D object.
  33620. */
  33621. function updateCamera( camera, parent ) {
  33622. if ( parent === null ) {
  33623. camera.matrixWorld.copy( camera.matrix );
  33624. } else {
  33625. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  33626. }
  33627. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33628. }
  33629. /**
  33630. * Updates the given camera with the transfomration of the XR camera and parent object.
  33631. *
  33632. * @inner
  33633. * @param {Camera} camera - The camera to update.
  33634. * @param {ArrayCamera} cameraXR - The XR camera.
  33635. * @param {Object3D} parent - The parent 3D object.
  33636. */
  33637. function updateUserCamera( camera, cameraXR, parent ) {
  33638. if ( parent === null ) {
  33639. camera.matrix.copy( cameraXR.matrixWorld );
  33640. } else {
  33641. camera.matrix.copy( parent.matrixWorld );
  33642. camera.matrix.invert();
  33643. camera.matrix.multiply( cameraXR.matrixWorld );
  33644. }
  33645. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33646. camera.updateMatrixWorld( true );
  33647. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  33648. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  33649. if ( camera.isPerspectiveCamera ) {
  33650. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  33651. camera.zoom = 1;
  33652. }
  33653. }
  33654. function onSessionEvent( event ) {
  33655. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  33656. if ( controllerIndex === - 1 ) {
  33657. return;
  33658. }
  33659. const controller = this._controllers[ controllerIndex ];
  33660. if ( controller !== undefined ) {
  33661. const referenceSpace = this.getReferenceSpace();
  33662. controller.update( event.inputSource, event.frame, referenceSpace );
  33663. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  33664. }
  33665. }
  33666. function onSessionEnd() {
  33667. const session = this._session;
  33668. const renderer = this._renderer;
  33669. session.removeEventListener( 'select', this._onSessionEvent );
  33670. session.removeEventListener( 'selectstart', this._onSessionEvent );
  33671. session.removeEventListener( 'selectend', this._onSessionEvent );
  33672. session.removeEventListener( 'squeeze', this._onSessionEvent );
  33673. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  33674. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  33675. session.removeEventListener( 'end', this._onSessionEnd );
  33676. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33677. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33678. const inputSource = this._controllerInputSources[ i ];
  33679. if ( inputSource === null ) continue;
  33680. this._controllerInputSources[ i ] = null;
  33681. this._controllers[ i ].disconnect( inputSource );
  33682. }
  33683. this._currentDepthNear = null;
  33684. this._currentDepthFar = null;
  33685. // restore framebuffer/rendering state
  33686. renderer.setRenderTarget( this._currentRenderTarget );
  33687. this._session = null;
  33688. this._xrRenderTarget = null;
  33689. //
  33690. this.isPresenting = false;
  33691. renderer._animation.stop();
  33692. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  33693. renderer._animation.setContext( this._currentAnimationContext );
  33694. renderer._animation.start();
  33695. renderer.setPixelRatio( this._currentPixelRatio );
  33696. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  33697. renderer.setXRTarget( null );
  33698. this.dispatchEvent( { type: 'sessionend' } );
  33699. }
  33700. function onInputSourcesChange( event ) {
  33701. const controllers = this._controllers;
  33702. const controllerInputSources = this._controllerInputSources;
  33703. // Notify disconnected
  33704. for ( let i = 0; i < event.removed.length; i ++ ) {
  33705. const inputSource = event.removed[ i ];
  33706. const index = controllerInputSources.indexOf( inputSource );
  33707. if ( index >= 0 ) {
  33708. controllerInputSources[ index ] = null;
  33709. controllers[ index ].disconnect( inputSource );
  33710. }
  33711. }
  33712. // Notify connected
  33713. for ( let i = 0; i < event.added.length; i ++ ) {
  33714. const inputSource = event.added[ i ];
  33715. let controllerIndex = controllerInputSources.indexOf( inputSource );
  33716. if ( controllerIndex === - 1 ) {
  33717. // Assign input source a controller that currently has no input source
  33718. for ( let i = 0; i < controllers.length; i ++ ) {
  33719. if ( i >= controllerInputSources.length ) {
  33720. controllerInputSources.push( inputSource );
  33721. controllerIndex = i;
  33722. break;
  33723. } else if ( controllerInputSources[ i ] === null ) {
  33724. controllerInputSources[ i ] = inputSource;
  33725. controllerIndex = i;
  33726. break;
  33727. }
  33728. }
  33729. // If all controllers do currently receive input we ignore new ones
  33730. if ( controllerIndex === - 1 ) break;
  33731. }
  33732. const controller = controllers[ controllerIndex ];
  33733. if ( controller ) {
  33734. controller.connect( inputSource );
  33735. }
  33736. }
  33737. }
  33738. function onAnimationFrame( time, frame ) {
  33739. if ( frame === undefined ) return;
  33740. const cameraXR = this._cameraXR;
  33741. const renderer = this._renderer;
  33742. const glBaseLayer = this._glBaseLayer;
  33743. const referenceSpace = this.getReferenceSpace();
  33744. const pose = frame.getViewerPose( referenceSpace );
  33745. this._xrFrame = frame;
  33746. if ( pose !== null ) {
  33747. const views = pose.views;
  33748. renderer.setXRTarget( glBaseLayer.framebuffer );
  33749. renderer.setRenderTarget( this._xrRenderTarget );
  33750. let cameraXRNeedsUpdate = false;
  33751. // check if it's necessary to rebuild cameraXR's camera list
  33752. if ( views.length !== cameraXR.cameras.length ) {
  33753. cameraXR.cameras.length = 0;
  33754. cameraXRNeedsUpdate = true;
  33755. }
  33756. for ( let i = 0; i < views.length; i ++ ) {
  33757. const view = views[ i ];
  33758. const viewport = glBaseLayer.getViewport( view );
  33759. let camera = this._cameras[ i ];
  33760. if ( camera === undefined ) {
  33761. camera = new PerspectiveCamera();
  33762. camera.layers.enable( i );
  33763. camera.viewport = new Vector4();
  33764. this._cameras[ i ] = camera;
  33765. }
  33766. camera.matrix.fromArray( view.transform.matrix );
  33767. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33768. camera.projectionMatrix.fromArray( view.projectionMatrix );
  33769. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33770. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  33771. if ( i === 0 ) {
  33772. cameraXR.matrix.copy( camera.matrix );
  33773. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  33774. }
  33775. if ( cameraXRNeedsUpdate === true ) {
  33776. cameraXR.cameras.push( camera );
  33777. }
  33778. }
  33779. }
  33780. //
  33781. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33782. const inputSource = this._controllerInputSources[ i ];
  33783. const controller = this._controllers[ i ];
  33784. if ( inputSource !== null && controller !== undefined ) {
  33785. controller.update( inputSource, frame, referenceSpace );
  33786. }
  33787. }
  33788. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  33789. if ( frame.detectedPlanes ) {
  33790. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  33791. }
  33792. this._xrFrame = null;
  33793. }
  33794. /** @module Renderer **/
  33795. const _scene = /*@__PURE__*/ new Scene();
  33796. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  33797. const _screen = /*@__PURE__*/ new Vector4();
  33798. const _frustum = /*@__PURE__*/ new Frustum();
  33799. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33800. const _vector4 = /*@__PURE__*/ new Vector4();
  33801. /**
  33802. * Base class for renderers.
  33803. */
  33804. class Renderer {
  33805. /**
  33806. * Constructs a new renderer.
  33807. *
  33808. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  33809. * @param {Object} parameters - The configuration parameter.
  33810. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  33811. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  33812. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  33813. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  33814. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  33815. * @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
  33816. * to overwrite the default.
  33817. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33818. */
  33819. constructor( backend, parameters = {} ) {
  33820. /**
  33821. * This flag can be used for type testing.
  33822. *
  33823. * @type {Boolean}
  33824. * @readonly
  33825. * @default true
  33826. */
  33827. this.isRenderer = true;
  33828. //
  33829. const {
  33830. logarithmicDepthBuffer = false,
  33831. alpha = true,
  33832. depth = true,
  33833. stencil = false,
  33834. antialias = false,
  33835. samples = 0,
  33836. getFallback = null
  33837. } = parameters;
  33838. /**
  33839. * A reference to the canvas element the renderer is drawing to.
  33840. * This value of this property will automatically be created by
  33841. * the renderer.
  33842. *
  33843. * @type {HTMLCanvasElement|OffscreenCanvas}
  33844. */
  33845. this.domElement = backend.getDomElement();
  33846. /**
  33847. * A reference to the current backend.
  33848. *
  33849. * @type {Backend}
  33850. */
  33851. this.backend = backend;
  33852. /**
  33853. * The number of MSAA samples.
  33854. *
  33855. * @type {Number}
  33856. * @default 0
  33857. */
  33858. this.samples = samples || ( antialias === true ) ? 4 : 0;
  33859. /**
  33860. * Whether the renderer should automatically clear the current rendering target
  33861. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  33862. * or the current bound render target (custom framebuffer).
  33863. *
  33864. * @type {Boolean}
  33865. * @default true
  33866. */
  33867. this.autoClear = true;
  33868. /**
  33869. * When `autoClear` is set to `true`, this property defines whether the renderer
  33870. * should clear the color buffer.
  33871. *
  33872. * @type {Boolean}
  33873. * @default true
  33874. */
  33875. this.autoClearColor = true;
  33876. /**
  33877. * When `autoClear` is set to `true`, this property defines whether the renderer
  33878. * should clear the depth buffer.
  33879. *
  33880. * @type {Boolean}
  33881. * @default true
  33882. */
  33883. this.autoClearDepth = true;
  33884. /**
  33885. * When `autoClear` is set to `true`, this property defines whether the renderer
  33886. * should clear the stencil buffer.
  33887. *
  33888. * @type {Boolean}
  33889. * @default true
  33890. */
  33891. this.autoClearStencil = true;
  33892. /**
  33893. * Whether the default framebuffer should be transparent or opaque.
  33894. *
  33895. * @type {Boolean}
  33896. * @default true
  33897. */
  33898. this.alpha = alpha;
  33899. /**
  33900. * Whether logarithmic depth buffer is enabled or not.
  33901. *
  33902. * @type {Boolean}
  33903. * @default false
  33904. */
  33905. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  33906. /**
  33907. * Defines the output color space of the renderer.
  33908. *
  33909. * @type {String}
  33910. * @default SRGBColorSpace
  33911. */
  33912. this.outputColorSpace = SRGBColorSpace;
  33913. /**
  33914. * Defines the tone mapping of the renderer.
  33915. *
  33916. * @type {Number}
  33917. * @default NoToneMapping
  33918. */
  33919. this.toneMapping = NoToneMapping;
  33920. /**
  33921. * Defines the tone mapping exposure.
  33922. *
  33923. * @type {Number}
  33924. * @default 1
  33925. */
  33926. this.toneMappingExposure = 1.0;
  33927. /**
  33928. * Whether the renderer should sort its render lists or not.
  33929. *
  33930. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  33931. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  33932. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  33933. * e.g. manually determining each object's rendering order.
  33934. *
  33935. * @type {Boolean}
  33936. * @default true
  33937. */
  33938. this.sortObjects = true;
  33939. /**
  33940. * Whether the default framebuffer should have a depth buffer or not.
  33941. *
  33942. * @type {Boolean}
  33943. * @default true
  33944. */
  33945. this.depth = depth;
  33946. /**
  33947. * Whether the default framebuffer should have a stencil buffer or not.
  33948. *
  33949. * @type {Boolean}
  33950. * @default false
  33951. */
  33952. this.stencil = stencil;
  33953. /**
  33954. * Holds a series of statistical information about the GPU memory
  33955. * and the rendering process. Useful for debugging and monitoring.
  33956. *
  33957. * @type {Info}
  33958. */
  33959. this.info = new Info();
  33960. this.nodes = {
  33961. modelViewMatrix: null,
  33962. modelNormalViewMatrix: null
  33963. };
  33964. /**
  33965. * The node library defines how certain library objects like materials, lights
  33966. * or tone mapping functions are mapped to node types. This is required since
  33967. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  33968. * be part of the scene graph, they are internally represented as nodes for
  33969. * further processing.
  33970. *
  33971. * @type {NodeLibrary}
  33972. */
  33973. this.library = new NodeLibrary();
  33974. /**
  33975. * A map-like data structure for managing lights.
  33976. *
  33977. * @type {Lighting}
  33978. */
  33979. this.lighting = new Lighting();
  33980. // internals
  33981. /**
  33982. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33983. *
  33984. * @private
  33985. * @type {Function}
  33986. */
  33987. this._getFallback = getFallback;
  33988. /**
  33989. * The renderer's pixel ration.
  33990. *
  33991. * @private
  33992. * @type {Number}
  33993. * @default 1
  33994. */
  33995. this._pixelRatio = 1;
  33996. /**
  33997. * The width of the renderer's default framebuffer in logical pixel unit.
  33998. *
  33999. * @private
  34000. * @type {Number}
  34001. */
  34002. this._width = this.domElement.width;
  34003. /**
  34004. * The height of the renderer's default framebuffer in logical pixel unit.
  34005. *
  34006. * @private
  34007. * @type {Number}
  34008. */
  34009. this._height = this.domElement.height;
  34010. /**
  34011. * The viewport of the renderer in logical pixel unit.
  34012. *
  34013. * @private
  34014. * @type {Vector4}
  34015. */
  34016. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34017. /**
  34018. * The scissor rectangle of the renderer in logical pixel unit.
  34019. *
  34020. * @private
  34021. * @type {Vector4}
  34022. */
  34023. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34024. /**
  34025. * Whether the scissor test should be enabled or not.
  34026. *
  34027. * @private
  34028. * @type {Boolean}
  34029. */
  34030. this._scissorTest = false;
  34031. /**
  34032. * A reference to a renderer module for managing shader attributes.
  34033. *
  34034. * @private
  34035. * @type {Attributes?}
  34036. * @default null
  34037. */
  34038. this._attributes = null;
  34039. /**
  34040. * A reference to a renderer module for managing geometries.
  34041. *
  34042. * @private
  34043. * @type {Geometries?}
  34044. * @default null
  34045. */
  34046. this._geometries = null;
  34047. /**
  34048. * A reference to a renderer module for managing node related logic.
  34049. *
  34050. * @private
  34051. * @type {Nodes?}
  34052. * @default null
  34053. */
  34054. this._nodes = null;
  34055. /**
  34056. * A reference to a renderer module for managing the internal animation loop.
  34057. *
  34058. * @private
  34059. * @type {Animation?}
  34060. * @default null
  34061. */
  34062. this._animation = null;
  34063. /**
  34064. * A reference to a renderer module for managing shader program bindings.
  34065. *
  34066. * @private
  34067. * @type {Bindings?}
  34068. * @default null
  34069. */
  34070. this._bindings = null;
  34071. /**
  34072. * A reference to a renderer module for managing render objects.
  34073. *
  34074. * @private
  34075. * @type {RenderObjects?}
  34076. * @default null
  34077. */
  34078. this._objects = null;
  34079. /**
  34080. * A reference to a renderer module for managing render and compute pipelines.
  34081. *
  34082. * @private
  34083. * @type {Pipelines?}
  34084. * @default null
  34085. */
  34086. this._pipelines = null;
  34087. /**
  34088. * A reference to a renderer module for managing render bundles.
  34089. *
  34090. * @private
  34091. * @type {RenderBundles?}
  34092. * @default null
  34093. */
  34094. this._bundles = null;
  34095. /**
  34096. * A reference to a renderer module for managing render lists.
  34097. *
  34098. * @private
  34099. * @type {RenderLists?}
  34100. * @default null
  34101. */
  34102. this._renderLists = null;
  34103. /**
  34104. * A reference to a renderer module for managing render contexts.
  34105. *
  34106. * @private
  34107. * @type {RenderContexts?}
  34108. * @default null
  34109. */
  34110. this._renderContexts = null;
  34111. /**
  34112. * A reference to a renderer module for managing textures.
  34113. *
  34114. * @private
  34115. * @type {Textures?}
  34116. * @default null
  34117. */
  34118. this._textures = null;
  34119. /**
  34120. * A reference to a renderer module for backgrounds.
  34121. *
  34122. * @private
  34123. * @type {Background?}
  34124. * @default null
  34125. */
  34126. this._background = null;
  34127. /**
  34128. * This fullscreen quad is used for internal render passes
  34129. * like the tone mapping and color space output pass.
  34130. *
  34131. * @private
  34132. * @type {QuadMesh}
  34133. */
  34134. this._quad = new QuadMesh( new NodeMaterial() );
  34135. this._quad.material.name = 'Renderer_output';
  34136. /**
  34137. * A reference to the current render context.
  34138. *
  34139. * @private
  34140. * @type {RenderContext?}
  34141. * @default null
  34142. */
  34143. this._currentRenderContext = null;
  34144. /**
  34145. * A custom sort function for the opaque render list.
  34146. *
  34147. * @private
  34148. * @type {Function?}
  34149. * @default null
  34150. */
  34151. this._opaqueSort = null;
  34152. /**
  34153. * A custom sort function for the transparent render list.
  34154. *
  34155. * @private
  34156. * @type {Function?}
  34157. * @default null
  34158. */
  34159. this._transparentSort = null;
  34160. /**
  34161. * The framebuffer target.
  34162. *
  34163. * @private
  34164. * @type {RenderTarget?}
  34165. * @default null
  34166. */
  34167. this._frameBufferTarget = null;
  34168. const alphaClear = this.alpha === true ? 0 : 1;
  34169. /**
  34170. * The clear color value.
  34171. *
  34172. * @private
  34173. * @type {Color4}
  34174. */
  34175. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34176. /**
  34177. * The clear depth value.
  34178. *
  34179. * @private
  34180. * @type {Number}
  34181. * @default 1
  34182. */
  34183. this._clearDepth = 1;
  34184. /**
  34185. * The clear stencil value.
  34186. *
  34187. * @private
  34188. * @type {Number}
  34189. * @default 0
  34190. */
  34191. this._clearStencil = 0;
  34192. /**
  34193. * The current render target.
  34194. *
  34195. * @private
  34196. * @type {RenderTarget?}
  34197. * @default null
  34198. */
  34199. this._renderTarget = null;
  34200. /**
  34201. * The active cube face.
  34202. *
  34203. * @private
  34204. * @type {Number}
  34205. * @default 0
  34206. */
  34207. this._activeCubeFace = 0;
  34208. /**
  34209. * The active mipmap level.
  34210. *
  34211. * @private
  34212. * @type {Number}
  34213. * @default 0
  34214. */
  34215. this._activeMipmapLevel = 0;
  34216. /**
  34217. * The MRT setting.
  34218. *
  34219. * @private
  34220. * @type {MRTNode?}
  34221. * @default null
  34222. */
  34223. this._mrt = null;
  34224. /**
  34225. * This function defines how a render object is going
  34226. * to be rendered.
  34227. *
  34228. * @private
  34229. * @type {Function?}
  34230. * @default null
  34231. */
  34232. this._renderObjectFunction = null;
  34233. /**
  34234. * Used to keep track of the current render object function.
  34235. *
  34236. * @private
  34237. * @type {Function?}
  34238. * @default null
  34239. */
  34240. this._currentRenderObjectFunction = null;
  34241. /**
  34242. * Used to keep track of the current render bundle.
  34243. *
  34244. * @private
  34245. * @type {RenderBundle?}
  34246. * @default null
  34247. */
  34248. this._currentRenderBundle = null;
  34249. /**
  34250. * Next to `_renderObjectFunction()`, this function provides another hook
  34251. * for influencing the render process of a render object. It is meant for internal
  34252. * use and only relevant for `compileAsync()` right now. Instead of using
  34253. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34254. * a different function might be used which performs no draw but just the node
  34255. * and pipeline updates.
  34256. *
  34257. * @private
  34258. * @type {Function?}
  34259. * @default null
  34260. */
  34261. this._handleObjectFunction = this._renderObjectDirect;
  34262. /**
  34263. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34264. * lost is considered as a context lost. When this is set to `true`, rendering
  34265. * isn't possible anymore.
  34266. *
  34267. * @private
  34268. * @type {Boolean}
  34269. * @default false
  34270. */
  34271. this._isDeviceLost = false;
  34272. /**
  34273. * A callback function that defines what should happen when a device/context lost occurs.
  34274. *
  34275. * @type {Function}
  34276. */
  34277. this.onDeviceLost = this._onDeviceLost;
  34278. /**
  34279. * Whether the renderer has been initialized or not.
  34280. *
  34281. * @private
  34282. * @type {Boolean}
  34283. * @default false
  34284. */
  34285. this._initialized = false;
  34286. /**
  34287. * A reference to the promise which initializes the renderer.
  34288. *
  34289. * @private
  34290. * @type {Promise?}
  34291. * @default null
  34292. */
  34293. this._initPromise = null;
  34294. /**
  34295. * An array of compilation promises which are used in `compileAsync()`.
  34296. *
  34297. * @private
  34298. * @type {Array<Promise>?}
  34299. * @default null
  34300. */
  34301. this._compilationPromises = null;
  34302. /**
  34303. * Whether the renderer should render transparent render objects or not.
  34304. *
  34305. * @type {Boolean}
  34306. * @default true
  34307. */
  34308. this.transparent = true;
  34309. /**
  34310. * Whether the renderer should render opaque render objects or not.
  34311. *
  34312. * @type {Boolean}
  34313. * @default true
  34314. */
  34315. this.opaque = true;
  34316. /**
  34317. * Shadow map configuration
  34318. * @typedef {Object} ShadowMapConfig
  34319. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34320. * @property {Number} type - The shadow map type.
  34321. */
  34322. /**
  34323. * The renderer's shadow configuration.
  34324. *
  34325. * @type {module:Renderer~ShadowMapConfig}
  34326. */
  34327. this.shadowMap = {
  34328. enabled: false,
  34329. type: PCFShadowMap
  34330. };
  34331. /**
  34332. * XR configuration.
  34333. * @typedef {Object} XRConfig
  34334. * @property {Boolean} enabled - Whether to globally enable XR or not.
  34335. */
  34336. /**
  34337. * The renderer's XR manager.
  34338. *
  34339. * @type {XRManager}
  34340. */
  34341. this.xr = new XRManager( this );
  34342. /**
  34343. * Debug configuration.
  34344. * @typedef {Object} DebugConfig
  34345. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  34346. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  34347. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  34348. */
  34349. /**
  34350. * The renderer's debug configuration.
  34351. *
  34352. * @type {module:Renderer~DebugConfig}
  34353. */
  34354. this.debug = {
  34355. checkShaderErrors: true,
  34356. onShaderError: null,
  34357. getShaderAsync: async ( scene, camera, object ) => {
  34358. await this.compileAsync( scene, camera );
  34359. const renderList = this._renderLists.get( scene, camera );
  34360. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  34361. const material = scene.overrideMaterial || object.material;
  34362. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  34363. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  34364. return { fragmentShader, vertexShader };
  34365. }
  34366. };
  34367. }
  34368. /**
  34369. * Initializes the renderer so it is ready for usage.
  34370. *
  34371. * @async
  34372. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  34373. */
  34374. async init() {
  34375. if ( this._initialized ) {
  34376. throw new Error( 'Renderer: Backend has already been initialized.' );
  34377. }
  34378. if ( this._initPromise !== null ) {
  34379. return this._initPromise;
  34380. }
  34381. this._initPromise = new Promise( async ( resolve, reject ) => {
  34382. let backend = this.backend;
  34383. try {
  34384. await backend.init( this );
  34385. } catch ( error ) {
  34386. if ( this._getFallback !== null ) {
  34387. // try the fallback
  34388. try {
  34389. this.backend = backend = this._getFallback( error );
  34390. await backend.init( this );
  34391. } catch ( error ) {
  34392. reject( error );
  34393. return;
  34394. }
  34395. } else {
  34396. reject( error );
  34397. return;
  34398. }
  34399. }
  34400. this._nodes = new Nodes( this, backend );
  34401. this._animation = new Animation( this._nodes, this.info );
  34402. this._attributes = new Attributes( backend );
  34403. this._background = new Background( this, this._nodes );
  34404. this._geometries = new Geometries( this._attributes, this.info );
  34405. this._textures = new Textures( this, backend, this.info );
  34406. this._pipelines = new Pipelines( backend, this._nodes );
  34407. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  34408. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  34409. this._renderLists = new RenderLists( this.lighting );
  34410. this._bundles = new RenderBundles();
  34411. this._renderContexts = new RenderContexts();
  34412. //
  34413. this._animation.start();
  34414. this._initialized = true;
  34415. resolve();
  34416. } );
  34417. return this._initPromise;
  34418. }
  34419. /**
  34420. * The coordinate system of the renderer. The value of this property
  34421. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  34422. * `THREE.WebGPUCoordinateSystem`.
  34423. *
  34424. * @readonly
  34425. * @type {Number}
  34426. */
  34427. get coordinateSystem() {
  34428. return this.backend.coordinateSystem;
  34429. }
  34430. /**
  34431. * Compiles all materials in the given scene. This can be useful to avoid a
  34432. * phenomenon which is called "shader compilation stutter", which occurs when
  34433. * rendering an object with a new shader for the first time.
  34434. *
  34435. * If you want to add a 3D object to an existing scene, use the third optional
  34436. * parameter for applying the target scene. Note that the (target) scene's lighting
  34437. * and environment must be configured before calling this method.
  34438. *
  34439. * @async
  34440. * @param {Object3D} scene - The scene or 3D object to precompile.
  34441. * @param {Camera} camera - The camera that is used to render the scene.
  34442. * @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.
  34443. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  34444. */
  34445. async compileAsync( scene, camera, targetScene = null ) {
  34446. if ( this._isDeviceLost === true ) return;
  34447. if ( this._initialized === false ) await this.init();
  34448. // preserve render tree
  34449. const nodeFrame = this._nodes.nodeFrame;
  34450. const previousRenderId = nodeFrame.renderId;
  34451. const previousRenderContext = this._currentRenderContext;
  34452. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34453. const previousCompilationPromises = this._compilationPromises;
  34454. //
  34455. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34456. if ( targetScene === null ) targetScene = scene;
  34457. const renderTarget = this._renderTarget;
  34458. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  34459. const activeMipmapLevel = this._activeMipmapLevel;
  34460. const compilationPromises = [];
  34461. this._currentRenderContext = renderContext;
  34462. this._currentRenderObjectFunction = this.renderObject;
  34463. this._handleObjectFunction = this._createObjectPipeline;
  34464. this._compilationPromises = compilationPromises;
  34465. nodeFrame.renderId ++;
  34466. //
  34467. nodeFrame.update();
  34468. //
  34469. renderContext.depth = this.depth;
  34470. renderContext.stencil = this.stencil;
  34471. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34472. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34473. //
  34474. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34475. //
  34476. const renderList = this._renderLists.get( scene, camera );
  34477. renderList.begin();
  34478. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34479. // include lights from target scene
  34480. if ( targetScene !== scene ) {
  34481. targetScene.traverseVisible( function ( object ) {
  34482. if ( object.isLight && object.layers.test( camera.layers ) ) {
  34483. renderList.pushLight( object );
  34484. }
  34485. } );
  34486. }
  34487. renderList.finish();
  34488. //
  34489. if ( renderTarget !== null ) {
  34490. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34491. const renderTargetData = this._textures.get( renderTarget );
  34492. renderContext.textures = renderTargetData.textures;
  34493. renderContext.depthTexture = renderTargetData.depthTexture;
  34494. } else {
  34495. renderContext.textures = null;
  34496. renderContext.depthTexture = null;
  34497. }
  34498. //
  34499. this._background.update( sceneRef, renderList, renderContext );
  34500. // process render lists
  34501. const opaqueObjects = renderList.opaque;
  34502. const transparentObjects = renderList.transparent;
  34503. const transparentDoublePassObjects = renderList.transparentDoublePass;
  34504. const lightsNode = renderList.lightsNode;
  34505. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34506. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34507. // restore render tree
  34508. nodeFrame.renderId = previousRenderId;
  34509. this._currentRenderContext = previousRenderContext;
  34510. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34511. this._compilationPromises = previousCompilationPromises;
  34512. this._handleObjectFunction = this._renderObjectDirect;
  34513. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  34514. await Promise.all( compilationPromises );
  34515. }
  34516. /**
  34517. * Renders the scene in an async fashion.
  34518. *
  34519. * @async
  34520. * @param {Object3D} scene - The scene or 3D object to render.
  34521. * @param {Camera} camera - The camera.
  34522. * @return {Promise} A Promise that resolves when the render has been finished.
  34523. */
  34524. async renderAsync( scene, camera ) {
  34525. if ( this._initialized === false ) await this.init();
  34526. const renderContext = this._renderScene( scene, camera );
  34527. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  34528. }
  34529. /**
  34530. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  34531. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  34532. *
  34533. * @async
  34534. * @return {Promise} A Promise that resolves when synchronization has been finished.
  34535. */
  34536. async waitForGPU() {
  34537. await this.backend.waitForGPU();
  34538. }
  34539. /**
  34540. * Sets the given MRT configuration.
  34541. *
  34542. * @param {MRTNode} mrt - The MRT node to set.
  34543. * @return {Renderer} A reference to this renderer.
  34544. */
  34545. setMRT( mrt ) {
  34546. this._mrt = mrt;
  34547. return this;
  34548. }
  34549. /**
  34550. * Returns the MRT configuration.
  34551. *
  34552. * @return {MRTNode} The MRT configuration.
  34553. */
  34554. getMRT() {
  34555. return this._mrt;
  34556. }
  34557. /**
  34558. * Default implementation of the device lost callback.
  34559. *
  34560. * @private
  34561. * @param {Object} info - Information about the context lost.
  34562. */
  34563. _onDeviceLost( info ) {
  34564. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  34565. if ( info.reason ) {
  34566. errorMessage += `\nReason: ${info.reason}`;
  34567. }
  34568. console.error( errorMessage );
  34569. this._isDeviceLost = true;
  34570. }
  34571. /**
  34572. * Renders the given render bundle.
  34573. *
  34574. * @private
  34575. * @param {Object} bundle - Render bundle data.
  34576. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  34577. * @param {LightsNode} lightsNode - The current lights node.
  34578. */
  34579. _renderBundle( bundle, sceneRef, lightsNode ) {
  34580. const { bundleGroup, camera, renderList } = bundle;
  34581. const renderContext = this._currentRenderContext;
  34582. //
  34583. const renderBundle = this._bundles.get( bundleGroup, camera );
  34584. const renderBundleData = this.backend.get( renderBundle );
  34585. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  34586. //
  34587. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  34588. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  34589. renderBundleData.renderContexts.add( renderContext );
  34590. if ( renderBundleNeedsUpdate ) {
  34591. this.backend.beginBundle( renderContext );
  34592. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  34593. renderBundleData.renderObjects = [];
  34594. }
  34595. this._currentRenderBundle = renderBundle;
  34596. const opaqueObjects = renderList.opaque;
  34597. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34598. this._currentRenderBundle = null;
  34599. //
  34600. this.backend.finishBundle( renderContext, renderBundle );
  34601. renderBundleData.version = bundleGroup.version;
  34602. } else {
  34603. const { renderObjects } = renderBundleData;
  34604. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  34605. const renderObject = renderObjects[ i ];
  34606. if ( this._nodes.needsRefresh( renderObject ) ) {
  34607. this._nodes.updateBefore( renderObject );
  34608. this._nodes.updateForRender( renderObject );
  34609. this._bindings.updateForRender( renderObject );
  34610. this._nodes.updateAfter( renderObject );
  34611. }
  34612. }
  34613. }
  34614. this.backend.addBundle( renderContext, renderBundle );
  34615. }
  34616. /**
  34617. * Renders the scene or 3D object with the given camera. This method can only be called
  34618. * if the renderer has been initialized.
  34619. *
  34620. * The target of the method is the default framebuffer (meaning the canvas)
  34621. * or alternatively a render target when specified via `setRenderTarget()`.
  34622. *
  34623. * @param {Object3D} scene - The scene or 3D object to render.
  34624. * @param {Camera} camera - The camera to render the scene with.
  34625. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  34626. * Only returned when the renderer has not been initialized.
  34627. */
  34628. render( scene, camera ) {
  34629. if ( this._initialized === false ) {
  34630. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  34631. return this.renderAsync( scene, camera );
  34632. }
  34633. this._renderScene( scene, camera );
  34634. }
  34635. /**
  34636. * Returns an internal render target which is used when computing the output tone mapping
  34637. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  34638. * pass and not inline to achieve more correct results.
  34639. *
  34640. * @private
  34641. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  34642. */
  34643. _getFrameBufferTarget() {
  34644. const { currentToneMapping, currentColorSpace } = this;
  34645. const useToneMapping = currentToneMapping !== NoToneMapping;
  34646. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  34647. if ( useToneMapping === false && useColorSpace === false ) return null;
  34648. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  34649. const { depth, stencil } = this;
  34650. let frameBufferTarget = this._frameBufferTarget;
  34651. if ( frameBufferTarget === null ) {
  34652. frameBufferTarget = new RenderTarget( width, height, {
  34653. depthBuffer: depth,
  34654. stencilBuffer: stencil,
  34655. type: HalfFloatType, // FloatType
  34656. format: RGBAFormat,
  34657. colorSpace: LinearSRGBColorSpace,
  34658. generateMipmaps: false,
  34659. minFilter: LinearFilter,
  34660. magFilter: LinearFilter,
  34661. samples: this.samples
  34662. } );
  34663. frameBufferTarget.isPostProcessingRenderTarget = true;
  34664. this._frameBufferTarget = frameBufferTarget;
  34665. }
  34666. frameBufferTarget.depthBuffer = depth;
  34667. frameBufferTarget.stencilBuffer = stencil;
  34668. frameBufferTarget.setSize( width, height );
  34669. frameBufferTarget.viewport.copy( this._viewport );
  34670. frameBufferTarget.scissor.copy( this._scissor );
  34671. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  34672. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  34673. frameBufferTarget.scissorTest = this._scissorTest;
  34674. return frameBufferTarget;
  34675. }
  34676. /**
  34677. * Renders the scene or 3D object with the given camera.
  34678. *
  34679. * @private
  34680. * @param {Object3D} scene - The scene or 3D object to render.
  34681. * @param {Camera} camera - The camera to render the scene with.
  34682. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  34683. * @return {RenderContext} The current render context.
  34684. */
  34685. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  34686. if ( this._isDeviceLost === true ) return;
  34687. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  34688. // preserve render tree
  34689. const nodeFrame = this._nodes.nodeFrame;
  34690. const previousRenderId = nodeFrame.renderId;
  34691. const previousRenderContext = this._currentRenderContext;
  34692. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34693. //
  34694. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34695. const outputRenderTarget = this._renderTarget;
  34696. const activeCubeFace = this._activeCubeFace;
  34697. const activeMipmapLevel = this._activeMipmapLevel;
  34698. //
  34699. let renderTarget;
  34700. if ( frameBufferTarget !== null ) {
  34701. renderTarget = frameBufferTarget;
  34702. this.setRenderTarget( renderTarget );
  34703. } else {
  34704. renderTarget = outputRenderTarget;
  34705. }
  34706. //
  34707. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  34708. this._currentRenderContext = renderContext;
  34709. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  34710. //
  34711. this.info.calls ++;
  34712. this.info.render.calls ++;
  34713. this.info.render.frameCalls ++;
  34714. nodeFrame.renderId = this.info.calls;
  34715. //
  34716. const coordinateSystem = this.coordinateSystem;
  34717. const xr = this.xr;
  34718. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  34719. camera.coordinateSystem = coordinateSystem;
  34720. camera.updateProjectionMatrix();
  34721. if ( camera.isArrayCamera ) {
  34722. for ( const subCamera of camera.cameras ) {
  34723. subCamera.coordinateSystem = coordinateSystem;
  34724. subCamera.updateProjectionMatrix();
  34725. }
  34726. }
  34727. }
  34728. //
  34729. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  34730. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  34731. if ( xr.enabled === true && xr.isPresenting === true ) {
  34732. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  34733. camera = xr.getCamera(); // use XR camera for rendering
  34734. }
  34735. //
  34736. let viewport = this._viewport;
  34737. let scissor = this._scissor;
  34738. let pixelRatio = this._pixelRatio;
  34739. if ( renderTarget !== null ) {
  34740. viewport = renderTarget.viewport;
  34741. scissor = renderTarget.scissor;
  34742. pixelRatio = 1;
  34743. }
  34744. this.getDrawingBufferSize( _drawingBufferSize );
  34745. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  34746. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  34747. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  34748. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  34749. renderContext.viewportValue.width >>= activeMipmapLevel;
  34750. renderContext.viewportValue.height >>= activeMipmapLevel;
  34751. renderContext.viewportValue.minDepth = minDepth;
  34752. renderContext.viewportValue.maxDepth = maxDepth;
  34753. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  34754. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  34755. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  34756. renderContext.scissorValue.width >>= activeMipmapLevel;
  34757. renderContext.scissorValue.height >>= activeMipmapLevel;
  34758. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34759. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34760. //
  34761. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34762. //
  34763. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  34764. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  34765. const renderList = this._renderLists.get( scene, camera );
  34766. renderList.begin();
  34767. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34768. renderList.finish();
  34769. if ( this.sortObjects === true ) {
  34770. renderList.sort( this._opaqueSort, this._transparentSort );
  34771. }
  34772. //
  34773. if ( renderTarget !== null ) {
  34774. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34775. const renderTargetData = this._textures.get( renderTarget );
  34776. renderContext.textures = renderTargetData.textures;
  34777. renderContext.depthTexture = renderTargetData.depthTexture;
  34778. renderContext.width = renderTargetData.width;
  34779. renderContext.height = renderTargetData.height;
  34780. renderContext.renderTarget = renderTarget;
  34781. renderContext.depth = renderTarget.depthBuffer;
  34782. renderContext.stencil = renderTarget.stencilBuffer;
  34783. } else {
  34784. renderContext.textures = null;
  34785. renderContext.depthTexture = null;
  34786. renderContext.width = this.domElement.width;
  34787. renderContext.height = this.domElement.height;
  34788. renderContext.depth = this.depth;
  34789. renderContext.stencil = this.stencil;
  34790. }
  34791. renderContext.width >>= activeMipmapLevel;
  34792. renderContext.height >>= activeMipmapLevel;
  34793. renderContext.activeCubeFace = activeCubeFace;
  34794. renderContext.activeMipmapLevel = activeMipmapLevel;
  34795. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  34796. //
  34797. this._background.update( sceneRef, renderList, renderContext );
  34798. //
  34799. this.backend.beginRender( renderContext );
  34800. // process render lists
  34801. const {
  34802. bundles,
  34803. lightsNode,
  34804. transparentDoublePass: transparentDoublePassObjects,
  34805. transparent: transparentObjects,
  34806. opaque: opaqueObjects
  34807. } = renderList;
  34808. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  34809. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34810. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34811. // finish render pass
  34812. this.backend.finishRender( renderContext );
  34813. // restore render tree
  34814. nodeFrame.renderId = previousRenderId;
  34815. this._currentRenderContext = previousRenderContext;
  34816. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34817. //
  34818. if ( frameBufferTarget !== null ) {
  34819. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  34820. const quad = this._quad;
  34821. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  34822. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  34823. quad.material.needsUpdate = true;
  34824. }
  34825. this._renderScene( quad, quad.camera, false );
  34826. }
  34827. //
  34828. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  34829. //
  34830. return renderContext;
  34831. }
  34832. /**
  34833. * Returns the maximum available anisotropy for texture filtering.
  34834. *
  34835. * @return {Number} The maximum available anisotropy.
  34836. */
  34837. getMaxAnisotropy() {
  34838. return this.backend.getMaxAnisotropy();
  34839. }
  34840. /**
  34841. * Returns the active cube face.
  34842. *
  34843. * @return {Number} The active cube face.
  34844. */
  34845. getActiveCubeFace() {
  34846. return this._activeCubeFace;
  34847. }
  34848. /**
  34849. * Returns the active mipmap level.
  34850. *
  34851. * @return {Number} The active mipmap level.
  34852. */
  34853. getActiveMipmapLevel() {
  34854. return this._activeMipmapLevel;
  34855. }
  34856. /**
  34857. * Applications are advised to always define the animation loop
  34858. * with this method and not manually with `requestAnimationFrame()`
  34859. * for best compatibility.
  34860. *
  34861. * @async
  34862. * @param {Function} callback - The application's animation loop.
  34863. * @return {Promise} A Promise that resolves when the set has been executed.
  34864. */
  34865. async setAnimationLoop( callback ) {
  34866. if ( this._initialized === false ) await this.init();
  34867. this._animation.setAnimationLoop( callback );
  34868. }
  34869. /**
  34870. * Can be used to transfer buffer data from a storage buffer attribute
  34871. * from the GPU to the CPU in context of compute shaders.
  34872. *
  34873. * @async
  34874. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  34875. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  34876. */
  34877. async getArrayBufferAsync( attribute ) {
  34878. return await this.backend.getArrayBufferAsync( attribute );
  34879. }
  34880. /**
  34881. * Returns the rendering context.
  34882. *
  34883. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  34884. */
  34885. getContext() {
  34886. return this.backend.getContext();
  34887. }
  34888. /**
  34889. * Returns the pixel ratio.
  34890. *
  34891. * @return {Number} The pixel ratio.
  34892. */
  34893. getPixelRatio() {
  34894. return this._pixelRatio;
  34895. }
  34896. /**
  34897. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  34898. *
  34899. * @param {Vector2} target - The method writes the result in this target object.
  34900. * @return {Vector2} The drawing buffer size.
  34901. */
  34902. getDrawingBufferSize( target ) {
  34903. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  34904. }
  34905. /**
  34906. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  34907. *
  34908. * @param {Vector2} target - The method writes the result in this target object.
  34909. * @return {Vector2} The drawing buffer size.
  34910. */
  34911. getSize( target ) {
  34912. return target.set( this._width, this._height );
  34913. }
  34914. /**
  34915. * Sets the given pixel ration and resizes the canvas if necessary.
  34916. *
  34917. * @param {Number} [value=1] - The pixel ratio.
  34918. */
  34919. setPixelRatio( value = 1 ) {
  34920. if ( this._pixelRatio === value ) return;
  34921. this._pixelRatio = value;
  34922. this.setSize( this._width, this._height, false );
  34923. }
  34924. /**
  34925. * This method allows to define the drawing buffer size by specifying
  34926. * width, height and pixel ratio all at once. The size of the drawing
  34927. * buffer is computed with this formula:
  34928. * ````
  34929. * size.x = width * pixelRatio;
  34930. * size.y = height * pixelRatio;
  34931. *```
  34932. *
  34933. * @param {Number} width - The width in logical pixels.
  34934. * @param {Number} height - The height in logical pixels.
  34935. * @param {Number} pixelRatio - The pixel ratio.
  34936. */
  34937. setDrawingBufferSize( width, height, pixelRatio ) {
  34938. this._width = width;
  34939. this._height = height;
  34940. this._pixelRatio = pixelRatio;
  34941. this.domElement.width = Math.floor( width * pixelRatio );
  34942. this.domElement.height = Math.floor( height * pixelRatio );
  34943. this.setViewport( 0, 0, width, height );
  34944. if ( this._initialized ) this.backend.updateSize();
  34945. }
  34946. /**
  34947. * Sets the size of the renderer.
  34948. *
  34949. * @param {Number} width - The width in logical pixels.
  34950. * @param {Number} height - The height in logical pixels.
  34951. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  34952. */
  34953. setSize( width, height, updateStyle = true ) {
  34954. this._width = width;
  34955. this._height = height;
  34956. this.domElement.width = Math.floor( width * this._pixelRatio );
  34957. this.domElement.height = Math.floor( height * this._pixelRatio );
  34958. if ( updateStyle === true ) {
  34959. this.domElement.style.width = width + 'px';
  34960. this.domElement.style.height = height + 'px';
  34961. }
  34962. this.setViewport( 0, 0, width, height );
  34963. if ( this._initialized ) this.backend.updateSize();
  34964. }
  34965. /**
  34966. * Defines a manual sort function for the opaque render list.
  34967. * Pass `null` to use the default sort.
  34968. *
  34969. * @param {Function} method - The sort function.
  34970. */
  34971. setOpaqueSort( method ) {
  34972. this._opaqueSort = method;
  34973. }
  34974. /**
  34975. * Defines a manual sort function for the transparent render list.
  34976. * Pass `null` to use the default sort.
  34977. *
  34978. * @param {Function} method - The sort function.
  34979. */
  34980. setTransparentSort( method ) {
  34981. this._transparentSort = method;
  34982. }
  34983. /**
  34984. * Returns the scissor rectangle.
  34985. *
  34986. * @param {Vector4} target - The method writes the result in this target object.
  34987. * @return {Vector4} The scissor rectangle.
  34988. */
  34989. getScissor( target ) {
  34990. const scissor = this._scissor;
  34991. target.x = scissor.x;
  34992. target.y = scissor.y;
  34993. target.width = scissor.width;
  34994. target.height = scissor.height;
  34995. return target;
  34996. }
  34997. /**
  34998. * Defines the scissor rectangle.
  34999. *
  35000. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  35001. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  35002. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  35003. * @param {Number} width - The width of the scissor box in logical pixel unit.
  35004. * @param {Number} height - The height of the scissor box in logical pixel unit.
  35005. */
  35006. setScissor( x, y, width, height ) {
  35007. const scissor = this._scissor;
  35008. if ( x.isVector4 ) {
  35009. scissor.copy( x );
  35010. } else {
  35011. scissor.set( x, y, width, height );
  35012. }
  35013. }
  35014. /**
  35015. * Returns the scissor test value.
  35016. *
  35017. * @return {Boolean} Whether the scissor test should be enabled or not.
  35018. */
  35019. getScissorTest() {
  35020. return this._scissorTest;
  35021. }
  35022. /**
  35023. * Defines the scissor test.
  35024. *
  35025. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35026. */
  35027. setScissorTest( boolean ) {
  35028. this._scissorTest = boolean;
  35029. this.backend.setScissorTest( boolean );
  35030. }
  35031. /**
  35032. * Returns the viewport definition.
  35033. *
  35034. * @param {Vector4} target - The method writes the result in this target object.
  35035. * @return {Vector4} The viewport definition.
  35036. */
  35037. getViewport( target ) {
  35038. return target.copy( this._viewport );
  35039. }
  35040. /**
  35041. * Defines the viewport.
  35042. *
  35043. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35044. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35045. * @param {Number} width - The width of the viewport in logical pixel unit.
  35046. * @param {Number} height - The height of the viewport in logical pixel unit.
  35047. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35048. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35049. */
  35050. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35051. const viewport = this._viewport;
  35052. if ( x.isVector4 ) {
  35053. viewport.copy( x );
  35054. } else {
  35055. viewport.set( x, y, width, height );
  35056. }
  35057. viewport.minDepth = minDepth;
  35058. viewport.maxDepth = maxDepth;
  35059. }
  35060. /**
  35061. * Returns the clear color.
  35062. *
  35063. * @param {Color} target - The method writes the result in this target object.
  35064. * @return {Color} The clear color.
  35065. */
  35066. getClearColor( target ) {
  35067. return target.copy( this._clearColor );
  35068. }
  35069. /**
  35070. * Defines the clear color and optionally the clear alpha.
  35071. *
  35072. * @param {Color} color - The clear color.
  35073. * @param {Number} [alpha=1] - The clear alpha.
  35074. */
  35075. setClearColor( color, alpha = 1 ) {
  35076. this._clearColor.set( color );
  35077. this._clearColor.a = alpha;
  35078. }
  35079. /**
  35080. * Returns the clear alpha.
  35081. *
  35082. * @return {Number} The clear alpha.
  35083. */
  35084. getClearAlpha() {
  35085. return this._clearColor.a;
  35086. }
  35087. /**
  35088. * Defines the clear alpha.
  35089. *
  35090. * @param {Number} alpha - The clear alpha.
  35091. */
  35092. setClearAlpha( alpha ) {
  35093. this._clearColor.a = alpha;
  35094. }
  35095. /**
  35096. * Returns the clear depth.
  35097. *
  35098. * @return {Number} The clear depth.
  35099. */
  35100. getClearDepth() {
  35101. return this._clearDepth;
  35102. }
  35103. /**
  35104. * Defines the clear depth.
  35105. *
  35106. * @param {Number} depth - The clear depth.
  35107. */
  35108. setClearDepth( depth ) {
  35109. this._clearDepth = depth;
  35110. }
  35111. /**
  35112. * Returns the clear stencil.
  35113. *
  35114. * @return {Number} The clear stencil.
  35115. */
  35116. getClearStencil() {
  35117. return this._clearStencil;
  35118. }
  35119. /**
  35120. * Defines the clear stencil.
  35121. *
  35122. * @param {Number} stencil - The clear stencil.
  35123. */
  35124. setClearStencil( stencil ) {
  35125. this._clearStencil = stencil;
  35126. }
  35127. /**
  35128. * This method performs an occlusion query for the given 3D object.
  35129. * It returns `true` if the given 3D object is fully occluded by other
  35130. * 3D objects in the scene.
  35131. *
  35132. * @param {Object3D} object - The 3D object to test.
  35133. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35134. */
  35135. isOccluded( object ) {
  35136. const renderContext = this._currentRenderContext;
  35137. return renderContext && this.backend.isOccluded( renderContext, object );
  35138. }
  35139. /**
  35140. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35141. *
  35142. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35143. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35144. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35145. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35146. * Only returned when the renderer has not been initialized.
  35147. */
  35148. clear( color = true, depth = true, stencil = true ) {
  35149. if ( this._initialized === false ) {
  35150. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35151. return this.clearAsync( color, depth, stencil );
  35152. }
  35153. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35154. let renderContext = null;
  35155. if ( renderTarget !== null ) {
  35156. this._textures.updateRenderTarget( renderTarget );
  35157. const renderTargetData = this._textures.get( renderTarget );
  35158. renderContext = this._renderContexts.getForClear( renderTarget );
  35159. renderContext.textures = renderTargetData.textures;
  35160. renderContext.depthTexture = renderTargetData.depthTexture;
  35161. renderContext.width = renderTargetData.width;
  35162. renderContext.height = renderTargetData.height;
  35163. renderContext.renderTarget = renderTarget;
  35164. renderContext.depth = renderTarget.depthBuffer;
  35165. renderContext.stencil = renderTarget.stencilBuffer;
  35166. }
  35167. // #30329
  35168. renderContext.clearColorValue = this._clearColor;
  35169. this.backend.clear( color, depth, stencil, renderContext );
  35170. if ( renderTarget !== null && this._renderTarget === null ) {
  35171. // If a color space transform or tone mapping is required,
  35172. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35173. const quad = this._quad;
  35174. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35175. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35176. quad.material.needsUpdate = true;
  35177. }
  35178. this._renderScene( quad, quad.camera, false );
  35179. }
  35180. }
  35181. /**
  35182. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35183. *
  35184. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35185. * Only returned when the renderer has not been initialized.
  35186. */
  35187. clearColor() {
  35188. return this.clear( true, false, false );
  35189. }
  35190. /**
  35191. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35192. *
  35193. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35194. * Only returned when the renderer has not been initialized.
  35195. */
  35196. clearDepth() {
  35197. return this.clear( false, true, false );
  35198. }
  35199. /**
  35200. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35201. *
  35202. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35203. * Only returned when the renderer has not been initialized.
  35204. */
  35205. clearStencil() {
  35206. return this.clear( false, false, true );
  35207. }
  35208. /**
  35209. * Async version of {@link module:Renderer~Renderer#clear}.
  35210. *
  35211. * @async
  35212. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35213. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35214. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35215. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35216. */
  35217. async clearAsync( color = true, depth = true, stencil = true ) {
  35218. if ( this._initialized === false ) await this.init();
  35219. this.clear( color, depth, stencil );
  35220. }
  35221. /**
  35222. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35223. *
  35224. * @async
  35225. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35226. */
  35227. async clearColorAsync() {
  35228. this.clearAsync( true, false, false );
  35229. }
  35230. /**
  35231. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35232. *
  35233. * @async
  35234. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35235. */
  35236. async clearDepthAsync() {
  35237. this.clearAsync( false, true, false );
  35238. }
  35239. /**
  35240. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35241. *
  35242. * @async
  35243. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35244. */
  35245. async clearStencilAsync() {
  35246. this.clearAsync( false, false, true );
  35247. }
  35248. /**
  35249. * The current output tone mapping of the renderer. When a render target is set,
  35250. * the output tone mapping is always `NoToneMapping`.
  35251. *
  35252. * @type {Number}
  35253. */
  35254. get currentToneMapping() {
  35255. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35256. }
  35257. /**
  35258. * The current output color space of the renderer. When a render target is set,
  35259. * the output color space is always `LinearSRGBColorSpace`.
  35260. *
  35261. * @type {String}
  35262. */
  35263. get currentColorSpace() {
  35264. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35265. }
  35266. /**
  35267. * Frees all internal resources of the renderer. Call this method if the renderer
  35268. * is no longer in use by your app.
  35269. */
  35270. dispose() {
  35271. this.info.dispose();
  35272. this.backend.dispose();
  35273. this._animation.dispose();
  35274. this._objects.dispose();
  35275. this._pipelines.dispose();
  35276. this._nodes.dispose();
  35277. this._bindings.dispose();
  35278. this._renderLists.dispose();
  35279. this._renderContexts.dispose();
  35280. this._textures.dispose();
  35281. this.setRenderTarget( null );
  35282. this.setAnimationLoop( null );
  35283. }
  35284. /**
  35285. * Ensures the renderer is XR compatible.
  35286. *
  35287. * @async
  35288. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  35289. */
  35290. async makeXRCompatible() {
  35291. await this.backend.makeXRCompatible();
  35292. }
  35293. /**
  35294. * Sets the XR rendering destination.
  35295. *
  35296. * @param {WebGLFramebuffer} xrTarget - The XR target.
  35297. */
  35298. setXRTarget( xrTarget ) {
  35299. this.backend.setXRTarget( xrTarget );
  35300. }
  35301. /**
  35302. * Sets the given render target. Calling this method means the renderer does not
  35303. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35304. * Use `null` as the first argument to reset the state.
  35305. *
  35306. * @param {RenderTarget?} renderTarget - The render target to set.
  35307. * @param {Number} [activeCubeFace=0] - The active cube face.
  35308. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35309. */
  35310. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35311. this._renderTarget = renderTarget;
  35312. this._activeCubeFace = activeCubeFace;
  35313. this._activeMipmapLevel = activeMipmapLevel;
  35314. }
  35315. /**
  35316. * Returns the current render target.
  35317. *
  35318. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35319. */
  35320. getRenderTarget() {
  35321. return this._renderTarget;
  35322. }
  35323. /**
  35324. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35325. *
  35326. * @callback renderObjectFunction
  35327. * @param {Object3D} object - The 3D object.
  35328. * @param {Scene} scene - The scene the 3D object belongs to.
  35329. * @param {Camera} camera - The camera the object should be rendered with.
  35330. * @param {BufferGeometry} geometry - The object's geometry.
  35331. * @param {Material} material - The object's material.
  35332. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35333. * @param {LightsNode} lightsNode - The current lights node.
  35334. * @param {ClippingContext} clippingContext - The clipping context.
  35335. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35336. */
  35337. /**
  35338. * Sets the given render object function. Calling this method overwrites the default implementation
  35339. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  35340. * if you want to modify the way objects are rendered. For example you can define things like "every
  35341. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  35342. * The custom function must always call `renderObject()` in its implementation.
  35343. *
  35344. * Use `null` as the first argument to reset the state.
  35345. *
  35346. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  35347. */
  35348. setRenderObjectFunction( renderObjectFunction ) {
  35349. this._renderObjectFunction = renderObjectFunction;
  35350. }
  35351. /**
  35352. * Returns the current render object function.
  35353. *
  35354. * @return {Function?} The current render object function. Returns `null` if no function is set.
  35355. */
  35356. getRenderObjectFunction() {
  35357. return this._renderObjectFunction;
  35358. }
  35359. /**
  35360. * Execute a single or an array of compute nodes. This method can only be called
  35361. * if the renderer has been initialized.
  35362. *
  35363. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35364. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  35365. */
  35366. compute( computeNodes ) {
  35367. if ( this._isDeviceLost === true ) return;
  35368. if ( this._initialized === false ) {
  35369. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  35370. return this.computeAsync( computeNodes );
  35371. }
  35372. //
  35373. const nodeFrame = this._nodes.nodeFrame;
  35374. const previousRenderId = nodeFrame.renderId;
  35375. //
  35376. this.info.calls ++;
  35377. this.info.compute.calls ++;
  35378. this.info.compute.frameCalls ++;
  35379. nodeFrame.renderId = this.info.calls;
  35380. //
  35381. const backend = this.backend;
  35382. const pipelines = this._pipelines;
  35383. const bindings = this._bindings;
  35384. const nodes = this._nodes;
  35385. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  35386. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  35387. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  35388. }
  35389. backend.beginCompute( computeNodes );
  35390. for ( const computeNode of computeList ) {
  35391. // onInit
  35392. if ( pipelines.has( computeNode ) === false ) {
  35393. const dispose = () => {
  35394. computeNode.removeEventListener( 'dispose', dispose );
  35395. pipelines.delete( computeNode );
  35396. bindings.delete( computeNode );
  35397. nodes.delete( computeNode );
  35398. };
  35399. computeNode.addEventListener( 'dispose', dispose );
  35400. //
  35401. const onInitFn = computeNode.onInitFunction;
  35402. if ( onInitFn !== null ) {
  35403. onInitFn.call( computeNode, { renderer: this } );
  35404. }
  35405. }
  35406. nodes.updateForCompute( computeNode );
  35407. bindings.updateForCompute( computeNode );
  35408. const computeBindings = bindings.getForCompute( computeNode );
  35409. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  35410. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  35411. }
  35412. backend.finishCompute( computeNodes );
  35413. //
  35414. nodeFrame.renderId = previousRenderId;
  35415. }
  35416. /**
  35417. * Execute a single or an array of compute nodes.
  35418. *
  35419. * @async
  35420. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35421. * @return {Promise} A Promise that resolve when the compute has finished.
  35422. */
  35423. async computeAsync( computeNodes ) {
  35424. if ( this._initialized === false ) await this.init();
  35425. this.compute( computeNodes );
  35426. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  35427. }
  35428. /**
  35429. * Checks if the given feature is supported by the selected backend.
  35430. *
  35431. * @async
  35432. * @param {String} name - The feature's name.
  35433. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  35434. */
  35435. async hasFeatureAsync( name ) {
  35436. if ( this._initialized === false ) await this.init();
  35437. return this.backend.hasFeature( name );
  35438. }
  35439. /**
  35440. * Checks if the given feature is supported by the selected backend. If the
  35441. * renderer has not been initialized, this method always returns `false`.
  35442. *
  35443. * @param {String} name - The feature's name.
  35444. * @return {Boolean} Whether the feature is supported or not.
  35445. */
  35446. hasFeature( name ) {
  35447. if ( this._initialized === false ) {
  35448. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  35449. return false;
  35450. }
  35451. return this.backend.hasFeature( name );
  35452. }
  35453. /**
  35454. * Returns `true` when the renderer has been initialized.
  35455. *
  35456. * @return {Boolean} Whether the renderer has been initialized or not.
  35457. */
  35458. hasInitialized() {
  35459. return this._initialized;
  35460. }
  35461. /**
  35462. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35463. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35464. *
  35465. * @async
  35466. * @param {Texture} texture - The texture.
  35467. * @return {Promise} A Promise that resolves when the texture has been initialized.
  35468. */
  35469. async initTextureAsync( texture ) {
  35470. if ( this._initialized === false ) await this.init();
  35471. this._textures.updateTexture( texture );
  35472. }
  35473. /**
  35474. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35475. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35476. *
  35477. * This method can only be used if the renderer has been initialized.
  35478. *
  35479. * @param {Texture} texture - The texture.
  35480. */
  35481. initTexture( texture ) {
  35482. if ( this._initialized === false ) {
  35483. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  35484. }
  35485. this._textures.updateTexture( texture );
  35486. }
  35487. /**
  35488. * Copies the current bound framebuffer into the given texture.
  35489. *
  35490. * @param {FramebufferTexture} framebufferTexture - The texture.
  35491. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  35492. */
  35493. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  35494. if ( rectangle !== null ) {
  35495. if ( rectangle.isVector2 ) {
  35496. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  35497. } else if ( rectangle.isVector4 ) {
  35498. rectangle = _vector4.copy( rectangle ).floor();
  35499. } else {
  35500. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  35501. return;
  35502. }
  35503. } else {
  35504. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  35505. }
  35506. //
  35507. let renderContext = this._currentRenderContext;
  35508. let renderTarget;
  35509. if ( renderContext !== null ) {
  35510. renderTarget = renderContext.renderTarget;
  35511. } else {
  35512. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35513. if ( renderTarget !== null ) {
  35514. this._textures.updateRenderTarget( renderTarget );
  35515. renderContext = this._textures.get( renderTarget );
  35516. }
  35517. }
  35518. //
  35519. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  35520. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  35521. }
  35522. /**
  35523. * Copies data of source texture into a destination texture.
  35524. *
  35525. * @param {Texture} srcTexture - The source texture.
  35526. * @param {Texture} dstTexture - The destination texture.
  35527. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  35528. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  35529. * @param {Number} level - The mipmap level to copy.
  35530. */
  35531. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  35532. this._textures.updateTexture( srcTexture );
  35533. this._textures.updateTexture( dstTexture );
  35534. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  35535. }
  35536. /**
  35537. * Reads pixel data from the given render target.
  35538. *
  35539. * @async
  35540. * @param {RenderTarget} renderTarget - The render target to read from.
  35541. * @param {Number} x - The `x` coordinate of the copy region's origin.
  35542. * @param {Number} y - The `y` coordinate of the copy region's origin.
  35543. * @param {Number} width - The width of the copy region.
  35544. * @param {Number} height - The height of the copy region.
  35545. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  35546. * @param {Number} [faceIndex=0] - The active cube face index.
  35547. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  35548. */
  35549. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  35550. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  35551. }
  35552. /**
  35553. * Analyzes the given 3D object's hierarchy and builds render lists from the
  35554. * processed hierarchy.
  35555. *
  35556. * @param {Object3D} object - The 3D object to process (usually a scene).
  35557. * @param {Camera} camera - The camera the object is rendered with.
  35558. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  35559. * @param {RenderList} renderList - The current render list.
  35560. * @param {ClippingContext} clippingContext - The current clipping context.
  35561. */
  35562. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  35563. if ( object.visible === false ) return;
  35564. const visible = object.layers.test( camera.layers );
  35565. if ( visible ) {
  35566. if ( object.isGroup ) {
  35567. groupOrder = object.renderOrder;
  35568. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  35569. } else if ( object.isLOD ) {
  35570. if ( object.autoUpdate === true ) object.update( camera );
  35571. } else if ( object.isLight ) {
  35572. renderList.pushLight( object );
  35573. } else if ( object.isSprite ) {
  35574. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  35575. if ( this.sortObjects === true ) {
  35576. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  35577. }
  35578. const { geometry, material } = object;
  35579. if ( material.visible ) {
  35580. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35581. }
  35582. }
  35583. } else if ( object.isLineLoop ) {
  35584. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  35585. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  35586. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  35587. const { geometry, material } = object;
  35588. if ( this.sortObjects === true ) {
  35589. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  35590. _vector4
  35591. .copy( geometry.boundingSphere.center )
  35592. .applyMatrix4( object.matrixWorld )
  35593. .applyMatrix4( _projScreenMatrix );
  35594. }
  35595. if ( Array.isArray( material ) ) {
  35596. const groups = geometry.groups;
  35597. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  35598. const group = groups[ i ];
  35599. const groupMaterial = material[ group.materialIndex ];
  35600. if ( groupMaterial && groupMaterial.visible ) {
  35601. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  35602. }
  35603. }
  35604. } else if ( material.visible ) {
  35605. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35606. }
  35607. }
  35608. }
  35609. }
  35610. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  35611. const baseRenderList = renderList;
  35612. // replace render list
  35613. renderList = this._renderLists.get( object, camera );
  35614. renderList.begin();
  35615. baseRenderList.pushBundle( {
  35616. bundleGroup: object,
  35617. camera,
  35618. renderList,
  35619. } );
  35620. renderList.finish();
  35621. }
  35622. const children = object.children;
  35623. for ( let i = 0, l = children.length; i < l; i ++ ) {
  35624. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  35625. }
  35626. }
  35627. /**
  35628. * Renders the given render bundles.
  35629. *
  35630. * @private
  35631. * @param {Array<Object>} bundles - Array with render bundle data.
  35632. * @param {Scene} sceneRef - The scene the render bundles belong to.
  35633. * @param {LightsNode} lightsNode - The current lights node.
  35634. */
  35635. _renderBundles( bundles, sceneRef, lightsNode ) {
  35636. for ( const bundle of bundles ) {
  35637. this._renderBundle( bundle, sceneRef, lightsNode );
  35638. }
  35639. }
  35640. /**
  35641. * Renders the transparent objects from the given render lists.
  35642. *
  35643. * @private
  35644. * @param {Array<Object>} renderList - The transparent render list.
  35645. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  35646. * @param {Camera} camera - The camera the render list should be rendered with.
  35647. * @param {Scene} scene - The scene the render list belongs to.
  35648. * @param {LightsNode} lightsNode - The current lights node.
  35649. */
  35650. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  35651. if ( doublePassList.length > 0 ) {
  35652. // render back side
  35653. for ( const { material } of doublePassList ) {
  35654. material.side = BackSide;
  35655. }
  35656. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  35657. // render front side
  35658. for ( const { material } of doublePassList ) {
  35659. material.side = FrontSide;
  35660. }
  35661. this._renderObjects( renderList, camera, scene, lightsNode );
  35662. // restore
  35663. for ( const { material } of doublePassList ) {
  35664. material.side = DoubleSide;
  35665. }
  35666. } else {
  35667. this._renderObjects( renderList, camera, scene, lightsNode );
  35668. }
  35669. }
  35670. /**
  35671. * Renders the objects from the given render list.
  35672. *
  35673. * @private
  35674. * @param {Array<Object>} renderList - The render list.
  35675. * @param {Camera} camera - The camera the render list should be rendered with.
  35676. * @param {Scene} scene - The scene the render list belongs to.
  35677. * @param {LightsNode} lightsNode - The current lights node.
  35678. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35679. */
  35680. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  35681. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  35682. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  35683. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  35684. }
  35685. }
  35686. /**
  35687. * This method represents the default render object function that manages the render lifecycle
  35688. * of the object.
  35689. *
  35690. * @param {Object3D} object - The 3D object.
  35691. * @param {Scene} scene - The scene the 3D object belongs to.
  35692. * @param {Camera} camera - The camera the object should be rendered with.
  35693. * @param {BufferGeometry} geometry - The object's geometry.
  35694. * @param {Material} material - The object's material.
  35695. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35696. * @param {LightsNode} lightsNode - The current lights node.
  35697. * @param {ClippingContext} clippingContext - The clipping context.
  35698. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35699. */
  35700. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  35701. let overridePositionNode;
  35702. let overrideColorNode;
  35703. let overrideDepthNode;
  35704. //
  35705. object.onBeforeRender( this, scene, camera, geometry, material, group );
  35706. //
  35707. if ( scene.overrideMaterial !== null ) {
  35708. const overrideMaterial = scene.overrideMaterial;
  35709. if ( material.positionNode && material.positionNode.isNode ) {
  35710. overridePositionNode = overrideMaterial.positionNode;
  35711. overrideMaterial.positionNode = material.positionNode;
  35712. }
  35713. overrideMaterial.alphaTest = material.alphaTest;
  35714. overrideMaterial.alphaMap = material.alphaMap;
  35715. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  35716. if ( overrideMaterial.isShadowPassMaterial ) {
  35717. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  35718. if ( material.depthNode && material.depthNode.isNode ) {
  35719. overrideDepthNode = overrideMaterial.depthNode;
  35720. overrideMaterial.depthNode = material.depthNode;
  35721. }
  35722. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  35723. overrideColorNode = overrideMaterial.colorNode;
  35724. overrideMaterial.colorNode = material.castShadowNode;
  35725. }
  35726. }
  35727. material = overrideMaterial;
  35728. }
  35729. //
  35730. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  35731. material.side = BackSide;
  35732. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  35733. material.side = FrontSide;
  35734. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  35735. material.side = DoubleSide;
  35736. } else {
  35737. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  35738. }
  35739. //
  35740. if ( overridePositionNode !== undefined ) {
  35741. scene.overrideMaterial.positionNode = overridePositionNode;
  35742. }
  35743. if ( overrideDepthNode !== undefined ) {
  35744. scene.overrideMaterial.depthNode = overrideDepthNode;
  35745. }
  35746. if ( overrideColorNode !== undefined ) {
  35747. scene.overrideMaterial.colorNode = overrideColorNode;
  35748. }
  35749. //
  35750. object.onAfterRender( this, scene, camera, geometry, material, group );
  35751. }
  35752. /**
  35753. * This method represents the default `_handleObjectFunction` implementation which creates
  35754. * a render object from the given data and performs the draw command with the selected backend.
  35755. *
  35756. * @private
  35757. * @param {Object3D} object - The 3D object.
  35758. * @param {Material} material - The object's material.
  35759. * @param {Scene} scene - The scene the 3D object belongs to.
  35760. * @param {Camera} camera - The camera the object should be rendered with.
  35761. * @param {LightsNode} lightsNode - The current lights node.
  35762. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35763. * @param {ClippingContext} clippingContext - The clipping context.
  35764. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35765. */
  35766. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35767. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35768. renderObject.drawRange = object.geometry.drawRange;
  35769. renderObject.group = group;
  35770. //
  35771. const needsRefresh = this._nodes.needsRefresh( renderObject );
  35772. if ( needsRefresh ) {
  35773. this._nodes.updateBefore( renderObject );
  35774. this._geometries.updateForRender( renderObject );
  35775. this._nodes.updateForRender( renderObject );
  35776. this._bindings.updateForRender( renderObject );
  35777. }
  35778. this._pipelines.updateForRender( renderObject );
  35779. //
  35780. if ( this._currentRenderBundle !== null ) {
  35781. const renderBundleData = this.backend.get( this._currentRenderBundle );
  35782. renderBundleData.renderObjects.push( renderObject );
  35783. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  35784. }
  35785. this.backend.draw( renderObject, this.info );
  35786. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  35787. }
  35788. /**
  35789. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  35790. * Used in `compileAsync()`.
  35791. *
  35792. * @private
  35793. * @param {Object3D} object - The 3D object.
  35794. * @param {Material} material - The object's material.
  35795. * @param {Scene} scene - The scene the 3D object belongs to.
  35796. * @param {Camera} camera - The camera the object should be rendered with.
  35797. * @param {LightsNode} lightsNode - The current lights node.
  35798. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35799. * @param {ClippingContext} clippingContext - The clipping context.
  35800. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35801. */
  35802. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35803. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35804. renderObject.drawRange = object.geometry.drawRange;
  35805. renderObject.group = group;
  35806. //
  35807. this._nodes.updateBefore( renderObject );
  35808. this._geometries.updateForRender( renderObject );
  35809. this._nodes.updateForRender( renderObject );
  35810. this._bindings.updateForRender( renderObject );
  35811. this._pipelines.getForRender( renderObject, this._compilationPromises );
  35812. this._nodes.updateAfter( renderObject );
  35813. }
  35814. /**
  35815. * Alias for `compileAsync()`.
  35816. *
  35817. * @method
  35818. * @param {Object3D} scene - The scene or 3D object to precompile.
  35819. * @param {Camera} camera - The camera that is used to render the scene.
  35820. * @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.
  35821. * @return {Promise} A Promise that resolves when the compile has been finished.
  35822. */
  35823. get compile() {
  35824. return this.compileAsync;
  35825. }
  35826. }
  35827. /**
  35828. * A binding represents the connection between a resource (like a texture, sampler
  35829. * or uniform buffer) and the resource definition in a shader stage.
  35830. *
  35831. * This module is an abstract base class for all concrete bindings types.
  35832. *
  35833. * @abstract
  35834. * @private
  35835. */
  35836. class Binding {
  35837. /**
  35838. * Constructs a new binding.
  35839. *
  35840. * @param {String} [name=''] - The binding's name.
  35841. */
  35842. constructor( name = '' ) {
  35843. /**
  35844. * The binding's name.
  35845. *
  35846. * @type {String}
  35847. */
  35848. this.name = name;
  35849. /**
  35850. * A bitmask that defines in what shader stages the
  35851. * binding's resource is accessible.
  35852. *
  35853. * @type {Number}
  35854. */
  35855. this.visibility = 0;
  35856. }
  35857. /**
  35858. * Makes sure binding's resource is visible for the given shader stage.
  35859. *
  35860. * @param {Number} visibility - The shader stage.
  35861. */
  35862. setVisibility( visibility ) {
  35863. this.visibility |= visibility;
  35864. }
  35865. /**
  35866. * Clones the binding.
  35867. *
  35868. * @return {Binding} The cloned binding.
  35869. */
  35870. clone() {
  35871. return Object.assign( new this.constructor(), this );
  35872. }
  35873. }
  35874. /** @module BufferUtils **/
  35875. /**
  35876. * This function is usually called with the length in bytes of an array buffer.
  35877. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  35878. *
  35879. * @function
  35880. * @param {Number} floatLength - The buffer length.
  35881. * @return {Number} The padded length.
  35882. */
  35883. function getFloatLength( floatLength ) {
  35884. // ensure chunk size alignment (STD140 layout)
  35885. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  35886. }
  35887. /**
  35888. * Represents a buffer binding type.
  35889. *
  35890. * @private
  35891. * @abstract
  35892. * @augments Binding
  35893. */
  35894. class Buffer extends Binding {
  35895. /**
  35896. * Constructs a new buffer.
  35897. *
  35898. * @param {String} name - The buffer's name.
  35899. * @param {TypedArray} [buffer=null] - The buffer.
  35900. */
  35901. constructor( name, buffer = null ) {
  35902. super( name );
  35903. /**
  35904. * This flag can be used for type testing.
  35905. *
  35906. * @type {Boolean}
  35907. * @readonly
  35908. * @default true
  35909. */
  35910. this.isBuffer = true;
  35911. /**
  35912. * The bytes per element.
  35913. *
  35914. * @type {Number}
  35915. */
  35916. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  35917. /**
  35918. * A reference to the internal buffer.
  35919. *
  35920. * @private
  35921. * @type {TypedArray}
  35922. */
  35923. this._buffer = buffer;
  35924. }
  35925. /**
  35926. * The buffer's byte length.
  35927. *
  35928. * @type {Number}
  35929. * @readonly
  35930. */
  35931. get byteLength() {
  35932. return getFloatLength( this._buffer.byteLength );
  35933. }
  35934. /**
  35935. * A reference to the internal buffer.
  35936. *
  35937. * @type {Float32Array}
  35938. * @readonly
  35939. */
  35940. get buffer() {
  35941. return this._buffer;
  35942. }
  35943. /**
  35944. * Updates the binding.
  35945. *
  35946. * @return {Boolean} Whether the buffer has been updated and must be
  35947. * uploaded to the GPU.
  35948. */
  35949. update() {
  35950. return true;
  35951. }
  35952. }
  35953. /**
  35954. * Represents a uniform buffer binding type.
  35955. *
  35956. * @private
  35957. * @augments Buffer
  35958. */
  35959. class UniformBuffer extends Buffer {
  35960. /**
  35961. * Constructs a new uniform buffer.
  35962. *
  35963. * @param {String} name - The buffer's name.
  35964. * @param {TypedArray} [buffer=null] - The buffer.
  35965. */
  35966. constructor( name, buffer = null ) {
  35967. super( name, buffer );
  35968. /**
  35969. * This flag can be used for type testing.
  35970. *
  35971. * @type {Boolean}
  35972. * @readonly
  35973. * @default true
  35974. */
  35975. this.isUniformBuffer = true;
  35976. }
  35977. }
  35978. let _id$4 = 0;
  35979. /**
  35980. * A special form of uniform buffer binding type.
  35981. * It's buffer value is managed by a node object.
  35982. *
  35983. * @private
  35984. * @augments UniformBuffer
  35985. */
  35986. class NodeUniformBuffer extends UniformBuffer {
  35987. /**
  35988. * Constructs a new node-based uniform buffer.
  35989. *
  35990. * @param {BufferNode} nodeUniform - The uniform buffer node.
  35991. * @param {UniformGroupNode} groupNode - The uniform group node.
  35992. */
  35993. constructor( nodeUniform, groupNode ) {
  35994. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  35995. /**
  35996. * The uniform buffer node.
  35997. *
  35998. * @type {BufferNode}
  35999. */
  36000. this.nodeUniform = nodeUniform;
  36001. /**
  36002. * The uniform group node.
  36003. *
  36004. * @type {UniformGroupNode}
  36005. */
  36006. this.groupNode = groupNode;
  36007. }
  36008. /**
  36009. * The uniform buffer.
  36010. *
  36011. * @type {Float32Array}
  36012. */
  36013. get buffer() {
  36014. return this.nodeUniform.value;
  36015. }
  36016. }
  36017. /**
  36018. * This class represents a uniform buffer binding but with
  36019. * an API that allows to maintain individual uniform objects.
  36020. *
  36021. * @private
  36022. * @augments UniformBuffer
  36023. */
  36024. class UniformsGroup extends UniformBuffer {
  36025. /**
  36026. * Constructs a new uniforms group.
  36027. *
  36028. * @param {String} name - The group's name.
  36029. */
  36030. constructor( name ) {
  36031. super( name );
  36032. /**
  36033. * This flag can be used for type testing.
  36034. *
  36035. * @type {Boolean}
  36036. * @readonly
  36037. * @default true
  36038. */
  36039. this.isUniformsGroup = true;
  36040. /**
  36041. * An array with the raw uniform values.
  36042. *
  36043. * @private
  36044. * @type {Array<Number>?}
  36045. * @default null
  36046. */
  36047. this._values = null;
  36048. /**
  36049. * An array of uniform objects.
  36050. *
  36051. * The order of uniforms in this array must match the order of uniforms in the shader.
  36052. *
  36053. * @type {Array<Uniform>}
  36054. */
  36055. this.uniforms = [];
  36056. }
  36057. /**
  36058. * Adds a uniform to this group.
  36059. *
  36060. * @param {Uniform} uniform - The uniform to add.
  36061. * @return {UniformsGroup} A reference to this group.
  36062. */
  36063. addUniform( uniform ) {
  36064. this.uniforms.push( uniform );
  36065. return this;
  36066. }
  36067. /**
  36068. * Removes a uniform from this group.
  36069. *
  36070. * @param {Uniform} uniform - The uniform to remove.
  36071. * @return {UniformsGroup} A reference to this group.
  36072. */
  36073. removeUniform( uniform ) {
  36074. const index = this.uniforms.indexOf( uniform );
  36075. if ( index !== - 1 ) {
  36076. this.uniforms.splice( index, 1 );
  36077. }
  36078. return this;
  36079. }
  36080. /**
  36081. * An array with the raw uniform values.
  36082. *
  36083. * @type {Array<Number>}
  36084. */
  36085. get values() {
  36086. if ( this._values === null ) {
  36087. this._values = Array.from( this.buffer );
  36088. }
  36089. return this._values;
  36090. }
  36091. /**
  36092. * A Float32 array buffer with the uniform values.
  36093. *
  36094. * @type {Float32Array}
  36095. */
  36096. get buffer() {
  36097. let buffer = this._buffer;
  36098. if ( buffer === null ) {
  36099. const byteLength = this.byteLength;
  36100. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36101. this._buffer = buffer;
  36102. }
  36103. return buffer;
  36104. }
  36105. /**
  36106. * The byte length of the buffer with correct buffer alignment.
  36107. *
  36108. * @type {Number}
  36109. */
  36110. get byteLength() {
  36111. let offset = 0; // global buffer offset in bytes
  36112. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36113. const uniform = this.uniforms[ i ];
  36114. const { boundary, itemSize } = uniform;
  36115. // offset within a single chunk in bytes
  36116. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36117. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36118. // conformance tests
  36119. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36120. // check for chunk overflow
  36121. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36122. } else if ( chunkOffset % boundary !== 0 ) {
  36123. // check for correct alignment
  36124. offset += ( chunkOffset % boundary );
  36125. }
  36126. uniform.offset = ( offset / this.bytesPerElement );
  36127. offset += ( itemSize * this.bytesPerElement );
  36128. }
  36129. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36130. }
  36131. /**
  36132. * Updates this group by updating each uniform object of
  36133. * the internal uniform list. The uniform objects check if their
  36134. * values has actually changed so this method only returns
  36135. * `true` if there is a real value change.
  36136. *
  36137. * @return {Boolean} Whether the uniforms have been updated and
  36138. * must be uploaded to the GPU.
  36139. */
  36140. update() {
  36141. let updated = false;
  36142. for ( const uniform of this.uniforms ) {
  36143. if ( this.updateByType( uniform ) === true ) {
  36144. updated = true;
  36145. }
  36146. }
  36147. return updated;
  36148. }
  36149. /**
  36150. * Updates a given uniform by calling an update method matching
  36151. * the uniforms type.
  36152. *
  36153. * @param {Uniform} uniform - The uniform to update.
  36154. * @return {Boolean} Whether the uniform has been updated or not.
  36155. */
  36156. updateByType( uniform ) {
  36157. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36158. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36159. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36160. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36161. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36162. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36163. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36164. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36165. }
  36166. /**
  36167. * Updates a given Number uniform.
  36168. *
  36169. * @param {NumberUniform} uniform - The Number uniform.
  36170. * @return {Boolean} Whether the uniform has been updated or not.
  36171. */
  36172. updateNumber( uniform ) {
  36173. let updated = false;
  36174. const a = this.values;
  36175. const v = uniform.getValue();
  36176. const offset = uniform.offset;
  36177. const type = uniform.getType();
  36178. if ( a[ offset ] !== v ) {
  36179. const b = this._getBufferForType( type );
  36180. b[ offset ] = a[ offset ] = v;
  36181. updated = true;
  36182. }
  36183. return updated;
  36184. }
  36185. /**
  36186. * Updates a given Vector2 uniform.
  36187. *
  36188. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36189. * @return {Boolean} Whether the uniform has been updated or not.
  36190. */
  36191. updateVector2( uniform ) {
  36192. let updated = false;
  36193. const a = this.values;
  36194. const v = uniform.getValue();
  36195. const offset = uniform.offset;
  36196. const type = uniform.getType();
  36197. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36198. const b = this._getBufferForType( type );
  36199. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36200. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36201. updated = true;
  36202. }
  36203. return updated;
  36204. }
  36205. /**
  36206. * Updates a given Vector3 uniform.
  36207. *
  36208. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36209. * @return {Boolean} Whether the uniform has been updated or not.
  36210. */
  36211. updateVector3( uniform ) {
  36212. let updated = false;
  36213. const a = this.values;
  36214. const v = uniform.getValue();
  36215. const offset = uniform.offset;
  36216. const type = uniform.getType();
  36217. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36218. const b = this._getBufferForType( type );
  36219. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36220. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36221. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36222. updated = true;
  36223. }
  36224. return updated;
  36225. }
  36226. /**
  36227. * Updates a given Vector4 uniform.
  36228. *
  36229. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36230. * @return {Boolean} Whether the uniform has been updated or not.
  36231. */
  36232. updateVector4( uniform ) {
  36233. let updated = false;
  36234. const a = this.values;
  36235. const v = uniform.getValue();
  36236. const offset = uniform.offset;
  36237. const type = uniform.getType();
  36238. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36239. const b = this._getBufferForType( type );
  36240. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36241. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36242. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36243. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36244. updated = true;
  36245. }
  36246. return updated;
  36247. }
  36248. /**
  36249. * Updates a given Color uniform.
  36250. *
  36251. * @param {ColorUniform} uniform - The Color uniform.
  36252. * @return {Boolean} Whether the uniform has been updated or not.
  36253. */
  36254. updateColor( uniform ) {
  36255. let updated = false;
  36256. const a = this.values;
  36257. const c = uniform.getValue();
  36258. const offset = uniform.offset;
  36259. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36260. const b = this.buffer;
  36261. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36262. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36263. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36264. updated = true;
  36265. }
  36266. return updated;
  36267. }
  36268. /**
  36269. * Updates a given Matrix3 uniform.
  36270. *
  36271. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36272. * @return {Boolean} Whether the uniform has been updated or not.
  36273. */
  36274. updateMatrix3( uniform ) {
  36275. let updated = false;
  36276. const a = this.values;
  36277. const e = uniform.getValue().elements;
  36278. const offset = uniform.offset;
  36279. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36280. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36281. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36282. const b = this.buffer;
  36283. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36284. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36285. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36286. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36287. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36288. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36289. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36290. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36291. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36292. updated = true;
  36293. }
  36294. return updated;
  36295. }
  36296. /**
  36297. * Updates a given Matrix4 uniform.
  36298. *
  36299. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36300. * @return {Boolean} Whether the uniform has been updated or not.
  36301. */
  36302. updateMatrix4( uniform ) {
  36303. let updated = false;
  36304. const a = this.values;
  36305. const e = uniform.getValue().elements;
  36306. const offset = uniform.offset;
  36307. if ( arraysEqual( a, e, offset ) === false ) {
  36308. const b = this.buffer;
  36309. b.set( e, offset );
  36310. setArray( a, e, offset );
  36311. updated = true;
  36312. }
  36313. return updated;
  36314. }
  36315. /**
  36316. * Returns a typed array that matches the given data type.
  36317. *
  36318. * @param {String} type - The data type.
  36319. * @return {TypedArray} The typed array.
  36320. */
  36321. _getBufferForType( type ) {
  36322. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36323. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36324. return this.buffer;
  36325. }
  36326. }
  36327. /**
  36328. * Sets the values of the second array to the first array.
  36329. *
  36330. * @private
  36331. * @param {TypedArray} a - The first array.
  36332. * @param {TypedArray} b - The second array.
  36333. * @param {Number} offset - An index offset for the first array.
  36334. */
  36335. function setArray( a, b, offset ) {
  36336. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36337. a[ offset + i ] = b[ i ];
  36338. }
  36339. }
  36340. /**
  36341. * Returns `true` if the given arrays are equal.
  36342. *
  36343. * @private
  36344. * @param {TypedArray} a - The first array.
  36345. * @param {TypedArray} b - The second array.
  36346. * @param {Number} offset - An index offset for the first array.
  36347. * @return {Boolean} Whether the given arrays are equal or not.
  36348. */
  36349. function arraysEqual( a, b, offset ) {
  36350. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36351. if ( a[ offset + i ] !== b[ i ] ) return false;
  36352. }
  36353. return true;
  36354. }
  36355. let _id$3 = 0;
  36356. /**
  36357. * A special form of uniforms group that represents
  36358. * the individual uniforms as node-based uniforms.
  36359. *
  36360. * @private
  36361. * @augments UniformsGroup
  36362. */
  36363. class NodeUniformsGroup extends UniformsGroup {
  36364. /**
  36365. * Constructs a new node-based uniforms group.
  36366. *
  36367. * @param {String} name - The group's name.
  36368. * @param {UniformGroupNode} groupNode - The uniform group node.
  36369. */
  36370. constructor( name, groupNode ) {
  36371. super( name );
  36372. /**
  36373. * The group's ID.
  36374. *
  36375. * @type {Number}
  36376. */
  36377. this.id = _id$3 ++;
  36378. /**
  36379. * The uniform group node.
  36380. *
  36381. * @type {UniformGroupNode}
  36382. */
  36383. this.groupNode = groupNode;
  36384. /**
  36385. * This flag can be used for type testing.
  36386. *
  36387. * @type {Boolean}
  36388. * @readonly
  36389. * @default true
  36390. */
  36391. this.isNodeUniformsGroup = true;
  36392. }
  36393. }
  36394. let _id$2 = 0;
  36395. /**
  36396. * Represents a sampled texture binding type.
  36397. *
  36398. * @private
  36399. * @augments Binding
  36400. */
  36401. class SampledTexture extends Binding {
  36402. /**
  36403. * Constructs a new sampled texture.
  36404. *
  36405. * @param {String} name - The sampled texture's name.
  36406. * @param {Texture?} texture - The texture this binding is referring to.
  36407. */
  36408. constructor( name, texture ) {
  36409. super( name );
  36410. /**
  36411. * This identifier.
  36412. *
  36413. * @type {Number}
  36414. */
  36415. this.id = _id$2 ++;
  36416. /**
  36417. * The texture this binding is referring to.
  36418. *
  36419. * @type {Texture?}
  36420. */
  36421. this.texture = texture;
  36422. /**
  36423. * The binding's version.
  36424. *
  36425. * @type {Number}
  36426. */
  36427. this.version = texture ? texture.version : 0;
  36428. /**
  36429. * Whether the texture is a storage texture or not.
  36430. *
  36431. * @type {Boolean}
  36432. * @default false
  36433. */
  36434. this.store = false;
  36435. /**
  36436. * The binding's generation which is an additional version
  36437. * qualifier.
  36438. *
  36439. * @type {Number?}
  36440. * @default null
  36441. */
  36442. this.generation = null;
  36443. /**
  36444. * This flag can be used for type testing.
  36445. *
  36446. * @type {Boolean}
  36447. * @readonly
  36448. * @default true
  36449. */
  36450. this.isSampledTexture = true;
  36451. }
  36452. /**
  36453. * Returns `true` whether this binding requires an update for the
  36454. * given generation.
  36455. *
  36456. * @param {Number} generation - The generation.
  36457. * @return {Boolean} Whether an update is required or not.
  36458. */
  36459. needsBindingsUpdate( generation ) {
  36460. const { texture } = this;
  36461. if ( generation !== this.generation ) {
  36462. this.generation = generation;
  36463. return true;
  36464. }
  36465. return texture.isVideoTexture;
  36466. }
  36467. /**
  36468. * Updates the binding.
  36469. *
  36470. * @return {Boolean} Whether the texture has been updated and must be
  36471. * uploaded to the GPU.
  36472. */
  36473. update() {
  36474. const { texture, version } = this;
  36475. if ( version !== texture.version ) {
  36476. this.version = texture.version;
  36477. return true;
  36478. }
  36479. return false;
  36480. }
  36481. }
  36482. /**
  36483. * A special form of sampled texture binding type.
  36484. * It's texture value is managed by a node object.
  36485. *
  36486. * @private
  36487. * @augments SampledTexture
  36488. */
  36489. class NodeSampledTexture extends SampledTexture {
  36490. /**
  36491. * Constructs a new node-based sampled texture.
  36492. *
  36493. * @param {String} name - The textures's name.
  36494. * @param {TextureNode} textureNode - The texture node.
  36495. * @param {UniformGroupNode} groupNode - The uniform group node.
  36496. * @param {String?} [access=null] - The access type.
  36497. */
  36498. constructor( name, textureNode, groupNode, access = null ) {
  36499. super( name, textureNode ? textureNode.value : null );
  36500. /**
  36501. * The texture node.
  36502. *
  36503. * @type {TextureNode}
  36504. */
  36505. this.textureNode = textureNode;
  36506. /**
  36507. * The uniform group node.
  36508. *
  36509. * @type {UniformGroupNode}
  36510. */
  36511. this.groupNode = groupNode;
  36512. /**
  36513. * The access type.
  36514. *
  36515. * @type {String?}
  36516. * @default null
  36517. */
  36518. this.access = access;
  36519. }
  36520. /**
  36521. * Overwrites the default to additionally check if the node value has changed.
  36522. *
  36523. * @param {Number} generation - The generation.
  36524. * @return {Boolean} Whether an update is required or not.
  36525. */
  36526. needsBindingsUpdate( generation ) {
  36527. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  36528. }
  36529. /**
  36530. * Updates the binding.
  36531. *
  36532. * @return {Boolean} Whether the texture has been updated and must be
  36533. * uploaded to the GPU.
  36534. */
  36535. update() {
  36536. const { textureNode } = this;
  36537. if ( this.texture !== textureNode.value ) {
  36538. this.texture = textureNode.value;
  36539. return true;
  36540. }
  36541. return super.update();
  36542. }
  36543. }
  36544. /**
  36545. * A special form of sampled cube texture binding type.
  36546. * It's texture value is managed by a node object.
  36547. *
  36548. * @private
  36549. * @augments NodeSampledTexture
  36550. */
  36551. class NodeSampledCubeTexture extends NodeSampledTexture {
  36552. /**
  36553. * Constructs a new node-based sampled cube texture.
  36554. *
  36555. * @param {String} name - The textures's name.
  36556. * @param {TextureNode} textureNode - The texture node.
  36557. * @param {UniformGroupNode} groupNode - The uniform group node.
  36558. * @param {String?} [access=null] - The access type.
  36559. */
  36560. constructor( name, textureNode, groupNode, access = null ) {
  36561. super( name, textureNode, groupNode, access );
  36562. /**
  36563. * This flag can be used for type testing.
  36564. *
  36565. * @type {Boolean}
  36566. * @readonly
  36567. * @default true
  36568. */
  36569. this.isSampledCubeTexture = true;
  36570. }
  36571. }
  36572. /**
  36573. * A special form of sampled 3D texture binding type.
  36574. * It's texture value is managed by a node object.
  36575. *
  36576. * @private
  36577. * @augments NodeSampledTexture
  36578. */
  36579. class NodeSampledTexture3D extends NodeSampledTexture {
  36580. /**
  36581. * Constructs a new node-based sampled 3D texture.
  36582. *
  36583. * @param {String} name - The textures's name.
  36584. * @param {TextureNode} textureNode - The texture node.
  36585. * @param {UniformGroupNode} groupNode - The uniform group node.
  36586. * @param {String?} [access=null] - The access type.
  36587. */
  36588. constructor( name, textureNode, groupNode, access = null ) {
  36589. super( name, textureNode, groupNode, access );
  36590. /**
  36591. * This flag can be used for type testing.
  36592. *
  36593. * @type {Boolean}
  36594. * @readonly
  36595. * @default true
  36596. */
  36597. this.isSampledTexture3D = true;
  36598. }
  36599. }
  36600. const glslMethods = {
  36601. textureDimensions: 'textureSize',
  36602. equals: 'equal'
  36603. };
  36604. const precisionLib = {
  36605. low: 'lowp',
  36606. medium: 'mediump',
  36607. high: 'highp'
  36608. };
  36609. const supports$1 = {
  36610. swizzleAssign: true,
  36611. storageBuffer: false
  36612. };
  36613. const defaultPrecisions = `
  36614. precision highp float;
  36615. precision highp int;
  36616. precision highp sampler2D;
  36617. precision highp sampler3D;
  36618. precision highp samplerCube;
  36619. precision highp sampler2DArray;
  36620. precision highp usampler2D;
  36621. precision highp usampler3D;
  36622. precision highp usamplerCube;
  36623. precision highp usampler2DArray;
  36624. precision highp isampler2D;
  36625. precision highp isampler3D;
  36626. precision highp isamplerCube;
  36627. precision highp isampler2DArray;
  36628. precision lowp sampler2DShadow;
  36629. `;
  36630. /**
  36631. * A node builder targeting GLSL.
  36632. *
  36633. * This module generates GLSL shader code from node materials and also
  36634. * generates the respective bindings and vertex buffer definitions. These
  36635. * data are later used by the renderer to create render and compute pipelines
  36636. * for render objects.
  36637. *
  36638. * @augments NodeBuilder
  36639. */
  36640. class GLSLNodeBuilder extends NodeBuilder {
  36641. /**
  36642. * Constructs a new GLSL node builder renderer.
  36643. *
  36644. * @param {Object3D} object - The 3D object.
  36645. * @param {Renderer} renderer - The renderer.
  36646. */
  36647. constructor( object, renderer ) {
  36648. super( object, renderer, new GLSLNodeParser() );
  36649. /**
  36650. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  36651. * another dictionary which manages UBOs per group ('render','frame','object').
  36652. *
  36653. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  36654. */
  36655. this.uniformGroups = {};
  36656. /**
  36657. * An array that holds objects defining the varying and attribute data in
  36658. * context of Transform Feedback.
  36659. *
  36660. * @type {Object<String,Map<String,Object>>}
  36661. */
  36662. this.transforms = [];
  36663. /**
  36664. * A dictionary that holds for each shader stage a Map of used extensions.
  36665. *
  36666. * @type {Object<String,Map<String,Object>>}
  36667. */
  36668. this.extensions = {};
  36669. /**
  36670. * A dictionary that holds for each shader stage an Array of used builtins.
  36671. *
  36672. * @type {Object<String,Array<String>>}
  36673. */
  36674. this.builtins = { vertex: [], fragment: [], compute: [] };
  36675. /**
  36676. * Whether comparison in shader code are generated with methods or not.
  36677. *
  36678. * @type {Boolean}
  36679. * @default true
  36680. */
  36681. this.useComparisonMethod = true;
  36682. }
  36683. /**
  36684. * Checks if the given texture requires a manual conversion to the working color space.
  36685. *
  36686. * @param {Texture} texture - The texture to check.
  36687. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  36688. */
  36689. needsToWorkingColorSpace( texture ) {
  36690. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  36691. }
  36692. /**
  36693. * Returns the native shader method name for a given generic name.
  36694. *
  36695. * @param {String} method - The method name to resolve.
  36696. * @return {String} The resolved GLSL method name.
  36697. */
  36698. getMethod( method ) {
  36699. return glslMethods[ method ] || method;
  36700. }
  36701. /**
  36702. * Returns the output struct name. Not relevant for GLSL.
  36703. *
  36704. * @return {String}
  36705. */
  36706. getOutputStructName() {
  36707. return '';
  36708. }
  36709. /**
  36710. * Builds the given shader node.
  36711. *
  36712. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36713. * @return {String} The GLSL function code.
  36714. */
  36715. buildFunctionCode( shaderNode ) {
  36716. const layout = shaderNode.layout;
  36717. const flowData = this.flowShaderNode( shaderNode );
  36718. const parameters = [];
  36719. for ( const input of layout.inputs ) {
  36720. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36721. }
  36722. //
  36723. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36724. ${ flowData.vars }
  36725. ${ flowData.code }
  36726. return ${ flowData.result };
  36727. }`;
  36728. //
  36729. return code;
  36730. }
  36731. /**
  36732. * Setups the Pixel Buffer Object (PBO) for the given storage
  36733. * buffer node.
  36734. *
  36735. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  36736. */
  36737. setupPBO( storageBufferNode ) {
  36738. const attribute = storageBufferNode.value;
  36739. if ( attribute.pbo === undefined ) {
  36740. const originalArray = attribute.array;
  36741. const numElements = attribute.count * attribute.itemSize;
  36742. const { itemSize } = attribute;
  36743. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36744. let format = isInteger ? RedIntegerFormat : RedFormat;
  36745. if ( itemSize === 2 ) {
  36746. format = isInteger ? RGIntegerFormat : RGFormat;
  36747. } else if ( itemSize === 3 ) {
  36748. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36749. } else if ( itemSize === 4 ) {
  36750. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36751. }
  36752. const typeMap = {
  36753. Float32Array: FloatType,
  36754. Uint8Array: UnsignedByteType,
  36755. Uint16Array: UnsignedShortType,
  36756. Uint32Array: UnsignedIntType,
  36757. Int8Array: ByteType,
  36758. Int16Array: ShortType,
  36759. Int32Array: IntType,
  36760. Uint8ClampedArray: UnsignedByteType,
  36761. };
  36762. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36763. let height = Math.ceil( ( numElements / itemSize ) / width );
  36764. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36765. const newSize = width * height * itemSize;
  36766. const newArray = new originalArray.constructor( newSize );
  36767. newArray.set( originalArray, 0 );
  36768. attribute.array = newArray;
  36769. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36770. pboTexture.needsUpdate = true;
  36771. pboTexture.isPBOTexture = true;
  36772. const pbo = new TextureNode( pboTexture, null, null );
  36773. pbo.setPrecision( 'high' );
  36774. attribute.pboNode = pbo;
  36775. attribute.pbo = pbo.value;
  36776. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36777. }
  36778. }
  36779. /**
  36780. * Returns a GLSL snippet that represents the property name of the given node.
  36781. *
  36782. * @param {Node} node - The node.
  36783. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36784. * @return {String} The property name.
  36785. */
  36786. getPropertyName( node, shaderStage = this.shaderStage ) {
  36787. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36788. return shaderStage.charAt( 0 ) + '_' + node.name;
  36789. }
  36790. return super.getPropertyName( node, shaderStage );
  36791. }
  36792. /**
  36793. * Setups the Pixel Buffer Object (PBO) for the given storage
  36794. * buffer node.
  36795. *
  36796. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  36797. * @return {String} The property name.
  36798. */
  36799. generatePBO( storageArrayElementNode ) {
  36800. const { node, indexNode } = storageArrayElementNode;
  36801. const attribute = node.value;
  36802. if ( this.renderer.backend.has( attribute ) ) {
  36803. const attributeData = this.renderer.backend.get( attribute );
  36804. attributeData.pbo = attribute.pbo;
  36805. }
  36806. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36807. const textureName = this.getPropertyName( nodeUniform );
  36808. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  36809. const indexSnippet = indexNode.build( this, 'uint' );
  36810. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36811. let propertyName = elementNodeData.propertyName;
  36812. if ( propertyName === undefined ) {
  36813. // property element
  36814. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36815. propertyName = this.getPropertyName( nodeVar );
  36816. // property size
  36817. const bufferNodeData = this.getDataFromNode( node );
  36818. let propertySizeName = bufferNodeData.propertySizeName;
  36819. if ( propertySizeName === undefined ) {
  36820. propertySizeName = propertyName + 'Size';
  36821. this.getVarFromNode( node, propertySizeName, 'uint' );
  36822. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  36823. bufferNodeData.propertySizeName = propertySizeName;
  36824. }
  36825. //
  36826. const { itemSize } = attribute;
  36827. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36828. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36829. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36830. //
  36831. let prefix = 'vec4';
  36832. if ( attribute.pbo.type === UnsignedIntType ) {
  36833. prefix = 'uvec4';
  36834. } else if ( attribute.pbo.type === IntType ) {
  36835. prefix = 'ivec4';
  36836. }
  36837. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  36838. elementNodeData.propertyName = propertyName;
  36839. }
  36840. return propertyName;
  36841. }
  36842. /**
  36843. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  36844. *
  36845. * @param {Texture} texture - The texture.
  36846. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36847. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36848. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36849. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36850. * @return {String} The GLSL snippet.
  36851. */
  36852. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36853. if ( depthSnippet ) {
  36854. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36855. } else {
  36856. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36857. }
  36858. }
  36859. /**
  36860. * Generates the GLSL snippet for sampling/loading the given texture.
  36861. *
  36862. * @param {Texture} texture - The texture.
  36863. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36864. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36865. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36866. * @return {String} The GLSL snippet.
  36867. */
  36868. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36869. if ( texture.isDepthTexture ) {
  36870. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36871. } else {
  36872. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36873. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36874. }
  36875. }
  36876. /**
  36877. * Generates the GLSL snippet when sampling textures with explicit mip level.
  36878. *
  36879. * @param {Texture} texture - The texture.
  36880. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36881. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36882. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36883. * @return {String} The GLSL snippet.
  36884. */
  36885. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36886. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36887. }
  36888. /**
  36889. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  36890. *
  36891. * @param {Texture} texture - The texture.
  36892. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36893. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36894. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  36895. * @return {String} The GLSL snippet.
  36896. */
  36897. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  36898. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  36899. }
  36900. /**
  36901. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  36902. *
  36903. * @param {Texture} texture - The texture.
  36904. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36905. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36906. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  36907. * @return {String} The GLSL snippet.
  36908. */
  36909. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36910. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36911. }
  36912. /**
  36913. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  36914. * against a reference value.
  36915. *
  36916. * @param {Texture} texture - The texture.
  36917. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36918. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36919. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  36920. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  36921. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36922. * @return {String} The GLSL snippet.
  36923. */
  36924. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36925. if ( shaderStage === 'fragment' ) {
  36926. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36927. } else {
  36928. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36929. }
  36930. }
  36931. /**
  36932. * Returns the variables of the given shader stage as a GLSL string.
  36933. *
  36934. * @param {String} shaderStage - The shader stage.
  36935. * @return {String} The GLSL snippet that defines the variables.
  36936. */
  36937. getVars( shaderStage ) {
  36938. const snippets = [];
  36939. const vars = this.vars[ shaderStage ];
  36940. if ( vars !== undefined ) {
  36941. for ( const variable of vars ) {
  36942. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36943. }
  36944. }
  36945. return snippets.join( '\n\t' );
  36946. }
  36947. /**
  36948. * Returns the uniforms of the given shader stage as a GLSL string.
  36949. *
  36950. * @param {String} shaderStage - The shader stage.
  36951. * @return {String} The GLSL snippet that defines the uniforms.
  36952. */
  36953. getUniforms( shaderStage ) {
  36954. const uniforms = this.uniforms[ shaderStage ];
  36955. const bindingSnippets = [];
  36956. const uniformGroups = {};
  36957. for ( const uniform of uniforms ) {
  36958. let snippet = null;
  36959. let group = false;
  36960. if ( uniform.type === 'texture' ) {
  36961. const texture = uniform.node.value;
  36962. let typePrefix = '';
  36963. if ( texture.isDataTexture === true ) {
  36964. if ( texture.type === UnsignedIntType ) {
  36965. typePrefix = 'u';
  36966. } else if ( texture.type === IntType ) {
  36967. typePrefix = 'i';
  36968. }
  36969. }
  36970. if ( texture.compareFunction ) {
  36971. snippet = `sampler2DShadow ${ uniform.name };`;
  36972. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  36973. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  36974. } else {
  36975. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  36976. }
  36977. } else if ( uniform.type === 'cubeTexture' ) {
  36978. snippet = `samplerCube ${ uniform.name };`;
  36979. } else if ( uniform.type === 'texture3D' ) {
  36980. snippet = `sampler3D ${ uniform.name };`;
  36981. } else if ( uniform.type === 'buffer' ) {
  36982. const bufferNode = uniform.node;
  36983. const bufferType = this.getType( bufferNode.bufferType );
  36984. const bufferCount = bufferNode.bufferCount;
  36985. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  36986. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  36987. } else {
  36988. const vectorType = this.getVectorType( uniform.type );
  36989. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  36990. group = true;
  36991. }
  36992. const precision = uniform.node.precision;
  36993. if ( precision !== null ) {
  36994. snippet = precisionLib[ precision ] + ' ' + snippet;
  36995. }
  36996. if ( group ) {
  36997. snippet = '\t' + snippet;
  36998. const groupName = uniform.groupNode.name;
  36999. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37000. groupSnippets.push( snippet );
  37001. } else {
  37002. snippet = 'uniform ' + snippet;
  37003. bindingSnippets.push( snippet );
  37004. }
  37005. }
  37006. let output = '';
  37007. for ( const name in uniformGroups ) {
  37008. const groupSnippets = uniformGroups[ name ];
  37009. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37010. }
  37011. output += bindingSnippets.join( '\n' );
  37012. return output;
  37013. }
  37014. /**
  37015. * Returns the type for a given buffer attribute.
  37016. *
  37017. * @param {BufferAttribute} attribute - The buffer attribute.
  37018. * @return {String} The type.
  37019. */
  37020. getTypeFromAttribute( attribute ) {
  37021. let nodeType = super.getTypeFromAttribute( attribute );
  37022. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37023. let dataAttribute = attribute;
  37024. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37025. const array = dataAttribute.array;
  37026. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37027. nodeType = nodeType.slice( 1 );
  37028. }
  37029. }
  37030. return nodeType;
  37031. }
  37032. /**
  37033. * Returns the shader attributes of the given shader stage as a GLSL string.
  37034. *
  37035. * @param {String} shaderStage - The shader stage.
  37036. * @return {String} The GLSL snippet that defines the shader attributes.
  37037. */
  37038. getAttributes( shaderStage ) {
  37039. let snippet = '';
  37040. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37041. const attributes = this.getAttributesArray();
  37042. let location = 0;
  37043. for ( const attribute of attributes ) {
  37044. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37045. }
  37046. }
  37047. return snippet;
  37048. }
  37049. /**
  37050. * Returns the members of the given struct type node as a GLSL string.
  37051. *
  37052. * @param {StructTypeNode} struct - The struct type node.
  37053. * @return {String} The GLSL snippet that defines the struct members.
  37054. */
  37055. getStructMembers( struct ) {
  37056. const snippets = [];
  37057. const members = struct.getMemberTypes();
  37058. for ( let i = 0; i < members.length; i ++ ) {
  37059. const member = members[ i ];
  37060. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37061. }
  37062. return snippets.join( '\n' );
  37063. }
  37064. /**
  37065. * Returns the structs of the given shader stage as a GLSL string.
  37066. *
  37067. * @param {String} shaderStage - The shader stage.
  37068. * @return {String} The GLSL snippet that defines the structs.
  37069. */
  37070. getStructs( shaderStage ) {
  37071. const snippets = [];
  37072. const structs = this.structs[ shaderStage ];
  37073. if ( structs.length === 0 ) {
  37074. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37075. }
  37076. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37077. const struct = structs[ index ];
  37078. let snippet = '\n';
  37079. snippet += this.getStructMembers( struct );
  37080. snippet += '\n';
  37081. snippets.push( snippet );
  37082. }
  37083. return snippets.join( '\n\n' );
  37084. }
  37085. /**
  37086. * Returns the varyings of the given shader stage as a GLSL string.
  37087. *
  37088. * @param {String} shaderStage - The shader stage.
  37089. * @return {String} The GLSL snippet that defines the varyings.
  37090. */
  37091. getVaryings( shaderStage ) {
  37092. let snippet = '';
  37093. const varyings = this.varyings;
  37094. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37095. for ( const varying of varyings ) {
  37096. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37097. const type = this.getType( varying.type );
  37098. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37099. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37100. }
  37101. } else if ( shaderStage === 'fragment' ) {
  37102. for ( const varying of varyings ) {
  37103. if ( varying.needsInterpolation ) {
  37104. const type = this.getType( varying.type );
  37105. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37106. snippet += `${flat}in ${type} ${varying.name};\n`;
  37107. }
  37108. }
  37109. }
  37110. for ( const builtin of this.builtins[ shaderStage ] ) {
  37111. snippet += `${builtin};\n`;
  37112. }
  37113. return snippet;
  37114. }
  37115. /**
  37116. * Returns the vertex index builtin.
  37117. *
  37118. * @return {String} The vertex index.
  37119. */
  37120. getVertexIndex() {
  37121. return 'uint( gl_VertexID )';
  37122. }
  37123. /**
  37124. * Returns the instance index builtin.
  37125. *
  37126. * @return {String} The instance index.
  37127. */
  37128. getInstanceIndex() {
  37129. return 'uint( gl_InstanceID )';
  37130. }
  37131. /**
  37132. * Returns the invocation local index builtin.
  37133. *
  37134. * @return {String} The invocation local index.
  37135. */
  37136. getInvocationLocalIndex() {
  37137. const workgroupSize = this.object.workgroupSize;
  37138. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37139. return `uint( gl_InstanceID ) % ${size}u`;
  37140. }
  37141. /**
  37142. * Returns the draw index builtin.
  37143. *
  37144. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37145. */
  37146. getDrawIndex() {
  37147. const extensions = this.renderer.backend.extensions;
  37148. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37149. return 'uint( gl_DrawID )';
  37150. }
  37151. return null;
  37152. }
  37153. /**
  37154. * Returns the front facing builtin.
  37155. *
  37156. * @return {String} The front facing builtin.
  37157. */
  37158. getFrontFacing() {
  37159. return 'gl_FrontFacing';
  37160. }
  37161. /**
  37162. * Returns the frag coord builtin.
  37163. *
  37164. * @return {String} The frag coord builtin.
  37165. */
  37166. getFragCoord() {
  37167. return 'gl_FragCoord.xy';
  37168. }
  37169. /**
  37170. * Returns the frag depth builtin.
  37171. *
  37172. * @return {String} The frag depth builtin.
  37173. */
  37174. getFragDepth() {
  37175. return 'gl_FragDepth';
  37176. }
  37177. /**
  37178. * Enables the given extension.
  37179. *
  37180. * @param {String} name - The extension name.
  37181. * @param {String} behavior - The extension behavior.
  37182. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37183. */
  37184. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37185. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37186. if ( map.has( name ) === false ) {
  37187. map.set( name, {
  37188. name,
  37189. behavior
  37190. } );
  37191. }
  37192. }
  37193. /**
  37194. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37195. *
  37196. * @param {String} shaderStage - The shader stage.
  37197. * @return {String} The GLSL snippet that defines the enabled extensions.
  37198. */
  37199. getExtensions( shaderStage ) {
  37200. const snippets = [];
  37201. if ( shaderStage === 'vertex' ) {
  37202. const ext = this.renderer.backend.extensions;
  37203. const isBatchedMesh = this.object.isBatchedMesh;
  37204. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37205. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37206. }
  37207. }
  37208. const extensions = this.extensions[ shaderStage ];
  37209. if ( extensions !== undefined ) {
  37210. for ( const { name, behavior } of extensions.values() ) {
  37211. snippets.push( `#extension ${name} : ${behavior}` );
  37212. }
  37213. }
  37214. return snippets.join( '\n' );
  37215. }
  37216. /**
  37217. * Returns the clip distances builtin.
  37218. *
  37219. * @return {String} The clip distances builtin.
  37220. */
  37221. getClipDistance() {
  37222. return 'gl_ClipDistance';
  37223. }
  37224. /**
  37225. * Whether the requested feature is available or not.
  37226. *
  37227. * @param {String} name - The requested feature.
  37228. * @return {Boolean} Whether the requested feature is supported or not.
  37229. */
  37230. isAvailable( name ) {
  37231. let result = supports$1[ name ];
  37232. if ( result === undefined ) {
  37233. let extensionName;
  37234. result = false;
  37235. switch ( name ) {
  37236. case 'float32Filterable':
  37237. extensionName = 'OES_texture_float_linear';
  37238. break;
  37239. case 'clipDistance':
  37240. extensionName = 'WEBGL_clip_cull_distance';
  37241. break;
  37242. }
  37243. if ( extensionName !== undefined ) {
  37244. const extensions = this.renderer.backend.extensions;
  37245. if ( extensions.has( extensionName ) ) {
  37246. extensions.get( extensionName );
  37247. result = true;
  37248. }
  37249. }
  37250. supports$1[ name ] = result;
  37251. }
  37252. return result;
  37253. }
  37254. /**
  37255. * Whether to flip texture data along its vertical axis or not.
  37256. *
  37257. * @return {Boolean} Returns always `true` in context of GLSL.
  37258. */
  37259. isFlipY() {
  37260. return true;
  37261. }
  37262. /**
  37263. * Enables hardware clipping.
  37264. *
  37265. * @param {String} planeCount - The clipping plane count.
  37266. */
  37267. enableHardwareClipping( planeCount ) {
  37268. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37269. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37270. }
  37271. /**
  37272. * Registers a transform in context of Transform Feedback.
  37273. *
  37274. * @param {String} varyingName - The varying name.
  37275. * @param {AttributeNode} attributeNode - The attribute node.
  37276. */
  37277. registerTransform( varyingName, attributeNode ) {
  37278. this.transforms.push( { varyingName, attributeNode } );
  37279. }
  37280. /**
  37281. * Returns the transforms of the given shader stage as a GLSL string.
  37282. *
  37283. * @param {String} shaderStage - The shader stage.
  37284. * @return {String} The GLSL snippet that defines the transforms.
  37285. */
  37286. getTransforms( /* shaderStage */ ) {
  37287. const transforms = this.transforms;
  37288. let snippet = '';
  37289. for ( let i = 0; i < transforms.length; i ++ ) {
  37290. const transform = transforms[ i ];
  37291. const attributeName = this.getPropertyName( transform.attributeNode );
  37292. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37293. }
  37294. return snippet;
  37295. }
  37296. /**
  37297. * Returns a GLSL struct based on the given name and variables.
  37298. *
  37299. * @private
  37300. * @param {String} name - The struct name.
  37301. * @param {String} vars - The struct variables.
  37302. * @return {String} The GLSL snippet representing a struct.
  37303. */
  37304. _getGLSLUniformStruct( name, vars ) {
  37305. return `
  37306. layout( std140 ) uniform ${name} {
  37307. ${vars}
  37308. };`;
  37309. }
  37310. /**
  37311. * Returns a GLSL vertex shader based on the given shader data.
  37312. *
  37313. * @private
  37314. * @param {Object} shaderData - The shader data.
  37315. * @return {String} The vertex shader.
  37316. */
  37317. _getGLSLVertexCode( shaderData ) {
  37318. return `#version 300 es
  37319. ${ this.getSignature() }
  37320. // extensions
  37321. ${shaderData.extensions}
  37322. // precision
  37323. ${ defaultPrecisions }
  37324. // uniforms
  37325. ${shaderData.uniforms}
  37326. // varyings
  37327. ${shaderData.varyings}
  37328. // attributes
  37329. ${shaderData.attributes}
  37330. // codes
  37331. ${shaderData.codes}
  37332. void main() {
  37333. // vars
  37334. ${shaderData.vars}
  37335. // transforms
  37336. ${shaderData.transforms}
  37337. // flow
  37338. ${shaderData.flow}
  37339. gl_PointSize = 1.0;
  37340. }
  37341. `;
  37342. }
  37343. /**
  37344. * Returns a GLSL fragment shader based on the given shader data.
  37345. *
  37346. * @private
  37347. * @param {Object} shaderData - The shader data.
  37348. * @return {String} The vertex shader.
  37349. */
  37350. _getGLSLFragmentCode( shaderData ) {
  37351. return `#version 300 es
  37352. ${ this.getSignature() }
  37353. // precision
  37354. ${ defaultPrecisions }
  37355. // uniforms
  37356. ${shaderData.uniforms}
  37357. // varyings
  37358. ${shaderData.varyings}
  37359. // codes
  37360. ${shaderData.codes}
  37361. ${shaderData.structs}
  37362. void main() {
  37363. // vars
  37364. ${shaderData.vars}
  37365. // flow
  37366. ${shaderData.flow}
  37367. }
  37368. `;
  37369. }
  37370. /**
  37371. * Controls the code build of the shader stages.
  37372. */
  37373. buildCode() {
  37374. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37375. this.sortBindingGroups();
  37376. for ( const shaderStage in shadersData ) {
  37377. let flow = '// code\n\n';
  37378. flow += this.flowCode[ shaderStage ];
  37379. const flowNodes = this.flowNodes[ shaderStage ];
  37380. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37381. for ( const node of flowNodes ) {
  37382. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37383. const slotName = node.name;
  37384. if ( slotName ) {
  37385. if ( flow.length > 0 ) flow += '\n';
  37386. flow += `\t// flow -> ${ slotName }\n\t`;
  37387. }
  37388. flow += `${ flowSlotData.code }\n\t`;
  37389. if ( node === mainNode && shaderStage !== 'compute' ) {
  37390. flow += '// result\n\t';
  37391. if ( shaderStage === 'vertex' ) {
  37392. flow += 'gl_Position = ';
  37393. flow += `${ flowSlotData.result };`;
  37394. } else if ( shaderStage === 'fragment' ) {
  37395. if ( ! node.outputNode.isOutputStructNode ) {
  37396. flow += 'fragColor = ';
  37397. flow += `${ flowSlotData.result };`;
  37398. }
  37399. }
  37400. }
  37401. }
  37402. const stageData = shadersData[ shaderStage ];
  37403. stageData.extensions = this.getExtensions( shaderStage );
  37404. stageData.uniforms = this.getUniforms( shaderStage );
  37405. stageData.attributes = this.getAttributes( shaderStage );
  37406. stageData.varyings = this.getVaryings( shaderStage );
  37407. stageData.vars = this.getVars( shaderStage );
  37408. stageData.structs = this.getStructs( shaderStage );
  37409. stageData.codes = this.getCodes( shaderStage );
  37410. stageData.transforms = this.getTransforms( shaderStage );
  37411. stageData.flow = flow;
  37412. }
  37413. if ( this.material !== null ) {
  37414. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37415. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37416. } else {
  37417. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37418. }
  37419. }
  37420. /**
  37421. * This method is one of the more important ones since it's responsible
  37422. * for generating a matching binding instance for the given uniform node.
  37423. *
  37424. * These bindings are later used in the renderer to create bind groups
  37425. * and layouts.
  37426. *
  37427. * @param {UniformNode} node - The uniform node.
  37428. * @param {String} type - The node data type.
  37429. * @param {String} shaderStage - The shader stage.
  37430. * @param {String?} [name=null] - An optional uniform name.
  37431. * @return {NodeUniform} The node uniform object.
  37432. */
  37433. getUniformFromNode( node, type, shaderStage, name = null ) {
  37434. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37435. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37436. let uniformGPU = nodeData.uniformGPU;
  37437. if ( uniformGPU === undefined ) {
  37438. const group = node.groupNode;
  37439. const groupName = group.name;
  37440. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37441. if ( type === 'texture' ) {
  37442. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37443. bindings.push( uniformGPU );
  37444. } else if ( type === 'cubeTexture' ) {
  37445. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37446. bindings.push( uniformGPU );
  37447. } else if ( type === 'texture3D' ) {
  37448. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37449. bindings.push( uniformGPU );
  37450. } else if ( type === 'buffer' ) {
  37451. node.name = `NodeBuffer_${ node.id }`;
  37452. uniformNode.name = `buffer${ node.id }`;
  37453. const buffer = new NodeUniformBuffer( node, group );
  37454. buffer.name = node.name;
  37455. bindings.push( buffer );
  37456. uniformGPU = buffer;
  37457. } else {
  37458. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37459. let uniformsGroup = uniformsStage[ groupName ];
  37460. if ( uniformsGroup === undefined ) {
  37461. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37462. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37463. uniformsStage[ groupName ] = uniformsGroup;
  37464. bindings.push( uniformsGroup );
  37465. }
  37466. uniformGPU = this.getNodeUniform( uniformNode, type );
  37467. uniformsGroup.addUniform( uniformGPU );
  37468. }
  37469. nodeData.uniformGPU = uniformGPU;
  37470. }
  37471. return uniformNode;
  37472. }
  37473. }
  37474. let _vector2 = null;
  37475. let _color4 = null;
  37476. /**
  37477. * Most of the rendering related logic is implemented in the
  37478. * {@link module:Renderer} module and related management components.
  37479. * Sometimes it is required though to execute commands which are
  37480. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  37481. * This abstract base class defines an interface that encapsulates
  37482. * all backend-related logic. Derived classes for each backend must
  37483. * implement the interface.
  37484. *
  37485. * @abstract
  37486. * @private
  37487. */
  37488. class Backend {
  37489. /**
  37490. * Constructs a new backend.
  37491. *
  37492. * @param {Object} parameters - An object holding parameters for the backend.
  37493. */
  37494. constructor( parameters = {} ) {
  37495. /**
  37496. * The parameters of the backend.
  37497. *
  37498. * @type {Object}
  37499. */
  37500. this.parameters = Object.assign( {}, parameters );
  37501. /**
  37502. * This weak map holds backend-specific data of objects
  37503. * like textures, attributes or render targets.
  37504. *
  37505. * @type {WeakMap}
  37506. */
  37507. this.data = new WeakMap();
  37508. /**
  37509. * A reference to the renderer.
  37510. *
  37511. * @type {Renderer?}
  37512. * @default null
  37513. */
  37514. this.renderer = null;
  37515. /**
  37516. * A reference to the canvas element the renderer is drawing to.
  37517. *
  37518. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  37519. * @default null
  37520. */
  37521. this.domElement = null;
  37522. }
  37523. /**
  37524. * Initializes the backend so it is ready for usage. Concrete backends
  37525. * are supposed to implement their rendering context creation and related
  37526. * operations in this method.
  37527. *
  37528. * @async
  37529. * @param {Renderer} renderer - The renderer.
  37530. * @return {Promise} A Promise that resolves when the backend has been initialized.
  37531. */
  37532. async init( renderer ) {
  37533. this.renderer = renderer;
  37534. }
  37535. /**
  37536. * The coordinate system of the backend.
  37537. *
  37538. * @abstract
  37539. * @type {Number}
  37540. * @readonly
  37541. */
  37542. get coordinateSystem() {}
  37543. // render context
  37544. /**
  37545. * This method is executed at the beginning of a render call and
  37546. * can be used by the backend to prepare the state for upcoming
  37547. * draw calls.
  37548. *
  37549. * @abstract
  37550. * @param {RenderContext} renderContext - The render context.
  37551. */
  37552. beginRender( /*renderContext*/ ) {}
  37553. /**
  37554. * This method is executed at the end of a render call and
  37555. * can be used by the backend to finalize work after draw
  37556. * calls.
  37557. *
  37558. * @abstract
  37559. * @param {RenderContext} renderContext - The render context.
  37560. */
  37561. finishRender( /*renderContext*/ ) {}
  37562. /**
  37563. * This method is executed at the beginning of a compute call and
  37564. * can be used by the backend to prepare the state for upcoming
  37565. * compute tasks.
  37566. *
  37567. * @abstract
  37568. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37569. */
  37570. beginCompute( /*computeGroup*/ ) {}
  37571. /**
  37572. * This method is executed at the end of a compute call and
  37573. * can be used by the backend to finalize work after compute
  37574. * tasks.
  37575. *
  37576. * @abstract
  37577. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37578. */
  37579. finishCompute( /*computeGroup*/ ) {}
  37580. // render object
  37581. /**
  37582. * Executes a draw command for the given render object.
  37583. *
  37584. * @abstract
  37585. * @param {RenderObject} renderObject - The render object to draw.
  37586. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  37587. */
  37588. draw( /*renderObject, info*/ ) { }
  37589. // compute node
  37590. /**
  37591. * Executes a compute command for the given compute node.
  37592. *
  37593. * @abstract
  37594. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  37595. * @param {Node} computeNode - The compute node.
  37596. * @param {Array<BindGroup>} bindings - The bindings.
  37597. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37598. */
  37599. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  37600. // program
  37601. /**
  37602. * Creates a shader program from the given programmable stage.
  37603. *
  37604. * @abstract
  37605. * @param {ProgrammableStage} program - The programmable stage.
  37606. */
  37607. createProgram( /*program*/ ) { }
  37608. /**
  37609. * Destroys the shader program of the given programmable stage.
  37610. *
  37611. * @abstract
  37612. * @param {ProgrammableStage} program - The programmable stage.
  37613. */
  37614. destroyProgram( /*program*/ ) { }
  37615. // bindings
  37616. /**
  37617. * Creates bindings from the given bind group definition.
  37618. *
  37619. * @abstract
  37620. * @param {BindGroup} bindGroup - The bind group.
  37621. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37622. * @param {Number} cacheIndex - The cache index.
  37623. * @param {Number} version - The version.
  37624. */
  37625. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37626. /**
  37627. * Updates the given bind group definition.
  37628. *
  37629. * @abstract
  37630. * @param {BindGroup} bindGroup - The bind group.
  37631. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37632. * @param {Number} cacheIndex - The cache index.
  37633. * @param {Number} version - The version.
  37634. */
  37635. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37636. /**
  37637. * Updates a buffer binding.
  37638. *
  37639. * @abstract
  37640. * @param {Buffer} binding - The buffer binding to update.
  37641. */
  37642. updateBinding( /*binding*/ ) { }
  37643. // pipeline
  37644. /**
  37645. * Creates a render pipeline for the given render object.
  37646. *
  37647. * @abstract
  37648. * @param {RenderObject} renderObject - The render object.
  37649. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  37650. */
  37651. createRenderPipeline( /*renderObject, promises*/ ) { }
  37652. /**
  37653. * Creates a compute pipeline for the given compute node.
  37654. *
  37655. * @abstract
  37656. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37657. * @param {Array<BindGroup>} bindings - The bindings.
  37658. */
  37659. createComputePipeline( /*computePipeline, bindings*/ ) { }
  37660. // cache key
  37661. /**
  37662. * Returns `true` if the render pipeline requires an update.
  37663. *
  37664. * @abstract
  37665. * @param {RenderObject} renderObject - The render object.
  37666. * @return {Boolean} Whether the render pipeline requires an update or not.
  37667. */
  37668. needsRenderUpdate( /*renderObject*/ ) { }
  37669. /**
  37670. * Returns a cache key that is used to identify render pipelines.
  37671. *
  37672. * @abstract
  37673. * @param {RenderObject} renderObject - The render object.
  37674. * @return {String} The cache key.
  37675. */
  37676. getRenderCacheKey( /*renderObject*/ ) { }
  37677. // node builder
  37678. /**
  37679. * Returns a node builder for the given render object.
  37680. *
  37681. * @abstract
  37682. * @param {RenderObject} renderObject - The render object.
  37683. * @param {Renderer} renderer - The renderer.
  37684. * @return {NodeBuilder} The node builder.
  37685. */
  37686. createNodeBuilder( /*renderObject, renderer*/ ) { }
  37687. // textures
  37688. /**
  37689. * Creates a GPU sampler for the given texture.
  37690. *
  37691. * @abstract
  37692. * @param {Texture} texture - The texture to create the sampler for.
  37693. */
  37694. createSampler( /*texture*/ ) { }
  37695. /**
  37696. * Destroys the GPU sampler for the given texture.
  37697. *
  37698. * @abstract
  37699. * @param {Texture} texture - The texture to destroy the sampler for.
  37700. */
  37701. destroySampler( /*texture*/ ) {}
  37702. /**
  37703. * Creates a default texture for the given texture that can be used
  37704. * as a placeholder until the actual texture is ready for usage.
  37705. *
  37706. * @abstract
  37707. * @param {Texture} texture - The texture to create a default texture for.
  37708. */
  37709. createDefaultTexture( /*texture*/ ) { }
  37710. /**
  37711. * Defines a texture on the GPU for the given texture object.
  37712. *
  37713. * @abstract
  37714. * @param {Texture} texture - The texture.
  37715. * @param {Object} [options={}] - Optional configuration parameter.
  37716. */
  37717. createTexture( /*texture, options={}*/ ) { }
  37718. /**
  37719. * Uploads the updated texture data to the GPU.
  37720. *
  37721. * @abstract
  37722. * @param {Texture} texture - The texture.
  37723. * @param {Object} [options={}] - Optional configuration parameter.
  37724. */
  37725. updateTexture( /*texture, options = {}*/ ) { }
  37726. /**
  37727. * Generates mipmaps for the given texture.
  37728. *
  37729. * @abstract
  37730. * @param {Texture} texture - The texture.
  37731. */
  37732. generateMipmaps( /*texture*/ ) { }
  37733. /**
  37734. * Destroys the GPU data for the given texture object.
  37735. *
  37736. * @abstract
  37737. * @param {Texture} texture - The texture.
  37738. */
  37739. destroyTexture( /*texture*/ ) { }
  37740. /**
  37741. * Returns texture data as a typed array.
  37742. *
  37743. * @abstract
  37744. * @async
  37745. * @param {Texture} texture - The texture to copy.
  37746. * @param {Number} x - The x coordinate of the copy origin.
  37747. * @param {Number} y - The y coordinate of the copy origin.
  37748. * @param {Number} width - The width of the copy.
  37749. * @param {Number} height - The height of the copy.
  37750. * @param {Number} faceIndex - The face index.
  37751. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  37752. */
  37753. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  37754. /**
  37755. * Copies data of the given source texture to the given destination texture.
  37756. *
  37757. * @abstract
  37758. * @param {Texture} srcTexture - The source texture.
  37759. * @param {Texture} dstTexture - The destination texture.
  37760. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  37761. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  37762. * @param {Number} [level=0] - The mip level to copy.
  37763. */
  37764. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  37765. /**
  37766. * Copies the current bound framebuffer to the given texture.
  37767. *
  37768. * @abstract
  37769. * @param {Texture} texture - The destination texture.
  37770. * @param {RenderContext} renderContext - The render context.
  37771. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  37772. */
  37773. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  37774. // attributes
  37775. /**
  37776. * Creates the GPU buffer of a shader attribute.
  37777. *
  37778. * @abstract
  37779. * @param {BufferAttribute} attribute - The buffer attribute.
  37780. */
  37781. createAttribute( /*attribute*/ ) { }
  37782. /**
  37783. * Creates the GPU buffer of an indexed shader attribute.
  37784. *
  37785. * @abstract
  37786. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  37787. */
  37788. createIndexAttribute( /*attribute*/ ) { }
  37789. /**
  37790. * Creates the GPU buffer of a storage attribute.
  37791. *
  37792. * @abstract
  37793. * @param {BufferAttribute} attribute - The buffer attribute.
  37794. */
  37795. createStorageAttribute( /*attribute*/ ) { }
  37796. /**
  37797. * Updates the GPU buffer of a shader attribute.
  37798. *
  37799. * @abstract
  37800. * @param {BufferAttribute} attribute - The buffer attribute to update.
  37801. */
  37802. updateAttribute( /*attribute*/ ) { }
  37803. /**
  37804. * Destroys the GPU buffer of a shader attribute.
  37805. *
  37806. * @abstract
  37807. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  37808. */
  37809. destroyAttribute( /*attribute*/ ) { }
  37810. // canvas
  37811. /**
  37812. * Returns the backend's rendering context.
  37813. *
  37814. * @abstract
  37815. * @return {Object} The rendering context.
  37816. */
  37817. getContext() { }
  37818. /**
  37819. * Backends can use this method if they have to run
  37820. * logic when the renderer gets resized.
  37821. *
  37822. * @abstract
  37823. */
  37824. updateSize() { }
  37825. /**
  37826. * Updates the viewport with the values from the given render context.
  37827. *
  37828. * @abstract
  37829. * @param {RenderContext} renderContext - The render context.
  37830. */
  37831. updateViewport( /*renderContext*/ ) {}
  37832. // utils
  37833. /**
  37834. * Returns `true` if the given 3D object is fully occluded by other
  37835. * 3D objects in the scene. Backends must implement this method by using
  37836. * a Occlusion Query API.
  37837. *
  37838. * @abstract
  37839. * @param {RenderContext} renderContext - The render context.
  37840. * @param {Object3D} object - The 3D object to test.
  37841. * @return {Boolean} Whether the 3D object is fully occluded or not.
  37842. */
  37843. isOccluded( /*renderContext, object*/ ) {}
  37844. /**
  37845. * Resolves the time stamp for the given render context and type.
  37846. *
  37847. * @async
  37848. * @abstract
  37849. * @param {RenderContext} renderContext - The render context.
  37850. * @param {String} type - The render context.
  37851. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  37852. */
  37853. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  37854. /**
  37855. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37856. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37857. *
  37858. * @async
  37859. * @abstract
  37860. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37861. */
  37862. async waitForGPU() {}
  37863. /**
  37864. * This method performs a readback operation by moving buffer data from
  37865. * a storage buffer attribute from the GPU to the CPU.
  37866. *
  37867. * @async
  37868. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37869. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37870. */
  37871. async getArrayBufferAsync( /* attribute */ ) {}
  37872. /**
  37873. * Checks if the given feature is supported by the backend.
  37874. *
  37875. * @async
  37876. * @abstract
  37877. * @param {String} name - The feature's name.
  37878. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37879. */
  37880. async hasFeatureAsync( /*name*/ ) { }
  37881. /**
  37882. * Checks if the given feature is supported by the backend.
  37883. *
  37884. * @abstract
  37885. * @param {String} name - The feature's name.
  37886. * @return {Boolean} Whether the feature is supported or not.
  37887. */
  37888. hasFeature( /*name*/ ) {}
  37889. /**
  37890. * Returns the maximum anisotropy texture filtering value.
  37891. *
  37892. * @abstract
  37893. * @return {Number} The maximum anisotropy texture filtering value.
  37894. */
  37895. getMaxAnisotropy() {}
  37896. /**
  37897. * Returns the drawing buffer size.
  37898. *
  37899. * @return {Vector2} The drawing buffer size.
  37900. */
  37901. getDrawingBufferSize() {
  37902. _vector2 = _vector2 || new Vector2();
  37903. return this.renderer.getDrawingBufferSize( _vector2 );
  37904. }
  37905. /**
  37906. * Defines the scissor test.
  37907. *
  37908. * @abstract
  37909. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  37910. */
  37911. setScissorTest( /*boolean*/ ) { }
  37912. /**
  37913. * Returns the clear color and alpha into a single
  37914. * color object.
  37915. *
  37916. * @return {Color4} The clear color.
  37917. */
  37918. getClearColor() {
  37919. const renderer = this.renderer;
  37920. _color4 = _color4 || new Color4();
  37921. renderer.getClearColor( _color4 );
  37922. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  37923. return _color4;
  37924. }
  37925. /**
  37926. * Returns the DOM element. If no DOM element exists, the backend
  37927. * creates a new one.
  37928. *
  37929. * @return {HTMLCanvasElement} The DOM element.
  37930. */
  37931. getDomElement() {
  37932. let domElement = this.domElement;
  37933. if ( domElement === null ) {
  37934. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37935. // OffscreenCanvas does not have setAttribute, see #22811
  37936. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37937. this.domElement = domElement;
  37938. }
  37939. return domElement;
  37940. }
  37941. /**
  37942. * Sets a dictionary for the given object into the
  37943. * internal data structure.
  37944. *
  37945. * @param {Object} object - The object.
  37946. * @param {Object} value - The dictionary to set.
  37947. */
  37948. set( object, value ) {
  37949. this.data.set( object, value );
  37950. }
  37951. /**
  37952. * Returns the dictionary for the given object.
  37953. *
  37954. * @param {Object} object - The object.
  37955. * @return {Object} The object's dictionary.
  37956. */
  37957. get( object ) {
  37958. let map = this.data.get( object );
  37959. if ( map === undefined ) {
  37960. map = {};
  37961. this.data.set( object, map );
  37962. }
  37963. return map;
  37964. }
  37965. /**
  37966. * Checks if the given object has a dictionary
  37967. * with data defined.
  37968. *
  37969. * @param {Object} object - The object.
  37970. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  37971. */
  37972. has( object ) {
  37973. return this.data.has( object );
  37974. }
  37975. /**
  37976. * Deletes an object from the internal data structure.
  37977. *
  37978. * @param {Object} object - The object to delete.
  37979. */
  37980. delete( object ) {
  37981. this.data.delete( object );
  37982. }
  37983. /**
  37984. * Frees internal resources.
  37985. *
  37986. * @abstract
  37987. */
  37988. dispose() { }
  37989. }
  37990. let _id$1 = 0;
  37991. /**
  37992. * This module is internally used in context of compute shaders.
  37993. * This type of shader is not natively supported in WebGL 2 and
  37994. * thus implemented via Transform Feedback. `DualAttributeData`
  37995. * manages the related data.
  37996. *
  37997. * @private
  37998. */
  37999. class DualAttributeData {
  38000. constructor( attributeData, dualBuffer ) {
  38001. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38002. this.type = attributeData.type;
  38003. this.bufferType = attributeData.bufferType;
  38004. this.pbo = attributeData.pbo;
  38005. this.byteLength = attributeData.byteLength;
  38006. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38007. this.version = attributeData.version;
  38008. this.isInteger = attributeData.isInteger;
  38009. this.activeBufferIndex = 0;
  38010. this.baseId = attributeData.id;
  38011. }
  38012. get id() {
  38013. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38014. }
  38015. get bufferGPU() {
  38016. return this.buffers[ this.activeBufferIndex ];
  38017. }
  38018. get transformBuffer() {
  38019. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38020. }
  38021. switchBuffers() {
  38022. this.activeBufferIndex ^= 1;
  38023. }
  38024. }
  38025. /**
  38026. * A WebGL 2 backend utility module for managing shader attributes.
  38027. *
  38028. * @private
  38029. */
  38030. class WebGLAttributeUtils {
  38031. /**
  38032. * Constructs a new utility object.
  38033. *
  38034. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38035. */
  38036. constructor( backend ) {
  38037. /**
  38038. * A reference to the WebGL 2 backend.
  38039. *
  38040. * @type {WebGLBackend}
  38041. */
  38042. this.backend = backend;
  38043. }
  38044. /**
  38045. * Creates the GPU buffer for the given buffer attribute.
  38046. *
  38047. * @param {BufferAttribute} attribute - The buffer attribute.
  38048. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38049. */
  38050. createAttribute( attribute, bufferType ) {
  38051. const backend = this.backend;
  38052. const { gl } = backend;
  38053. const array = attribute.array;
  38054. const usage = attribute.usage || gl.STATIC_DRAW;
  38055. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38056. const bufferData = backend.get( bufferAttribute );
  38057. let bufferGPU = bufferData.bufferGPU;
  38058. if ( bufferGPU === undefined ) {
  38059. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38060. bufferData.bufferGPU = bufferGPU;
  38061. bufferData.bufferType = bufferType;
  38062. bufferData.version = bufferAttribute.version;
  38063. }
  38064. //attribute.onUploadCallback();
  38065. let type;
  38066. if ( array instanceof Float32Array ) {
  38067. type = gl.FLOAT;
  38068. } else if ( array instanceof Uint16Array ) {
  38069. if ( attribute.isFloat16BufferAttribute ) {
  38070. type = gl.HALF_FLOAT;
  38071. } else {
  38072. type = gl.UNSIGNED_SHORT;
  38073. }
  38074. } else if ( array instanceof Int16Array ) {
  38075. type = gl.SHORT;
  38076. } else if ( array instanceof Uint32Array ) {
  38077. type = gl.UNSIGNED_INT;
  38078. } else if ( array instanceof Int32Array ) {
  38079. type = gl.INT;
  38080. } else if ( array instanceof Int8Array ) {
  38081. type = gl.BYTE;
  38082. } else if ( array instanceof Uint8Array ) {
  38083. type = gl.UNSIGNED_BYTE;
  38084. } else if ( array instanceof Uint8ClampedArray ) {
  38085. type = gl.UNSIGNED_BYTE;
  38086. } else {
  38087. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38088. }
  38089. let attributeData = {
  38090. bufferGPU,
  38091. bufferType,
  38092. type,
  38093. byteLength: array.byteLength,
  38094. bytesPerElement: array.BYTES_PER_ELEMENT,
  38095. version: attribute.version,
  38096. pbo: attribute.pbo,
  38097. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38098. id: _id$1 ++
  38099. };
  38100. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38101. // create buffer for transform feedback use
  38102. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38103. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38104. }
  38105. backend.set( attribute, attributeData );
  38106. }
  38107. /**
  38108. * Updates the GPU buffer of the given buffer attribute.
  38109. *
  38110. * @param {BufferAttribute} attribute - The buffer attribute.
  38111. */
  38112. updateAttribute( attribute ) {
  38113. const backend = this.backend;
  38114. const { gl } = backend;
  38115. const array = attribute.array;
  38116. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38117. const bufferData = backend.get( bufferAttribute );
  38118. const bufferType = bufferData.bufferType;
  38119. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38120. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38121. if ( updateRanges.length === 0 ) {
  38122. // Not using update ranges
  38123. gl.bufferSubData( bufferType, 0, array );
  38124. } else {
  38125. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38126. const range = updateRanges[ i ];
  38127. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38128. array, range.start, range.count );
  38129. }
  38130. bufferAttribute.clearUpdateRanges();
  38131. }
  38132. gl.bindBuffer( bufferType, null );
  38133. bufferData.version = bufferAttribute.version;
  38134. }
  38135. /**
  38136. * Destroys the GPU buffer of the given buffer attribute.
  38137. *
  38138. * @param {BufferAttribute} attribute - The buffer attribute.
  38139. */
  38140. destroyAttribute( attribute ) {
  38141. const backend = this.backend;
  38142. const { gl } = backend;
  38143. if ( attribute.isInterleavedBufferAttribute ) {
  38144. backend.delete( attribute.data );
  38145. }
  38146. const attributeData = backend.get( attribute );
  38147. gl.deleteBuffer( attributeData.bufferGPU );
  38148. backend.delete( attribute );
  38149. }
  38150. /**
  38151. * This method performs a readback operation by moving buffer data from
  38152. * a storage buffer attribute from the GPU to the CPU.
  38153. *
  38154. * @async
  38155. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38156. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38157. */
  38158. async getArrayBufferAsync( attribute ) {
  38159. const backend = this.backend;
  38160. const { gl } = backend;
  38161. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38162. const { bufferGPU } = backend.get( bufferAttribute );
  38163. const array = attribute.array;
  38164. const byteLength = array.byteLength;
  38165. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38166. const writeBuffer = gl.createBuffer();
  38167. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38168. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38169. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38170. await backend.utils._clientWaitAsync();
  38171. const dstBuffer = new attribute.array.constructor( array.length );
  38172. // Ensure the buffer is bound before reading
  38173. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38174. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38175. gl.deleteBuffer( writeBuffer );
  38176. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38177. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38178. return dstBuffer.buffer;
  38179. }
  38180. /**
  38181. * Creates a WebGL buffer with the given data.
  38182. *
  38183. * @private
  38184. * @param {WebGL2RenderingContext} gl - The rendering context.
  38185. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38186. * @param {TypedArray} array - The array of the buffer attribute.
  38187. * @param {GLenum} usage - The usage.
  38188. * @return {WebGLBuffer} The WebGL buffer.
  38189. */
  38190. _createBuffer( gl, bufferType, array, usage ) {
  38191. const bufferGPU = gl.createBuffer();
  38192. gl.bindBuffer( bufferType, bufferGPU );
  38193. gl.bufferData( bufferType, array, usage );
  38194. gl.bindBuffer( bufferType, null );
  38195. return bufferGPU;
  38196. }
  38197. }
  38198. let initialized$1 = false, equationToGL, factorToGL;
  38199. /**
  38200. * A WebGL 2 backend utility module for managing the WebGL state.
  38201. *
  38202. * The major goal of this module is to reduce the number of state changes
  38203. * by caching the WEbGL state with a series of variables. In this way, the
  38204. * renderer only executes state change commands when necessary which
  38205. * improves the overall performance.
  38206. *
  38207. * @private
  38208. */
  38209. class WebGLState {
  38210. /**
  38211. * Constructs a new utility object.
  38212. *
  38213. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38214. */
  38215. constructor( backend ) {
  38216. /**
  38217. * A reference to the WebGL 2 backend.
  38218. *
  38219. * @type {WebGLBackend}
  38220. */
  38221. this.backend = backend;
  38222. /**
  38223. * A reference to the rendering context.
  38224. *
  38225. * @type {WebGL2RenderingContext}
  38226. */
  38227. this.gl = this.backend.gl;
  38228. // Below properties are intended to cache
  38229. // the WebGL state and are not explicitly
  38230. // documented for convenience reasons.
  38231. this.enabled = {};
  38232. this.currentFlipSided = null;
  38233. this.currentCullFace = null;
  38234. this.currentProgram = null;
  38235. this.currentBlendingEnabled = false;
  38236. this.currentBlending = null;
  38237. this.currentBlendSrc = null;
  38238. this.currentBlendDst = null;
  38239. this.currentBlendSrcAlpha = null;
  38240. this.currentBlendDstAlpha = null;
  38241. this.currentPremultipledAlpha = null;
  38242. this.currentPolygonOffsetFactor = null;
  38243. this.currentPolygonOffsetUnits = null;
  38244. this.currentColorMask = null;
  38245. this.currentDepthFunc = null;
  38246. this.currentDepthMask = null;
  38247. this.currentStencilFunc = null;
  38248. this.currentStencilRef = null;
  38249. this.currentStencilFuncMask = null;
  38250. this.currentStencilFail = null;
  38251. this.currentStencilZFail = null;
  38252. this.currentStencilZPass = null;
  38253. this.currentStencilMask = null;
  38254. this.currentLineWidth = null;
  38255. this.currentClippingPlanes = 0;
  38256. this.currentBoundFramebuffers = {};
  38257. this.currentDrawbuffers = new WeakMap();
  38258. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38259. this.currentTextureSlot = null;
  38260. this.currentBoundTextures = {};
  38261. this.currentBoundBufferBases = {};
  38262. if ( initialized$1 === false ) {
  38263. this._init();
  38264. initialized$1 = true;
  38265. }
  38266. }
  38267. /**
  38268. * Inits the state of the utility.
  38269. *
  38270. * @private
  38271. */
  38272. _init() {
  38273. const gl = this.gl;
  38274. // Store only WebGL constants here.
  38275. equationToGL = {
  38276. [ AddEquation ]: gl.FUNC_ADD,
  38277. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38278. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38279. };
  38280. factorToGL = {
  38281. [ ZeroFactor ]: gl.ZERO,
  38282. [ OneFactor ]: gl.ONE,
  38283. [ SrcColorFactor ]: gl.SRC_COLOR,
  38284. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38285. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38286. [ DstColorFactor ]: gl.DST_COLOR,
  38287. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38288. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38289. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38290. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38291. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38292. };
  38293. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38294. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38295. this.currentScissor = new Vector4().fromArray( scissorParam );
  38296. this.currentViewport = new Vector4().fromArray( viewportParam );
  38297. this._tempVec4 = new Vector4();
  38298. }
  38299. /**
  38300. * Enables the given WebGL capability.
  38301. *
  38302. * This method caches the capability state so
  38303. * `gl.enable()` is only called when necessary.
  38304. *
  38305. * @param {GLenum} id - The capability to enable.
  38306. */
  38307. enable( id ) {
  38308. const { enabled } = this;
  38309. if ( enabled[ id ] !== true ) {
  38310. this.gl.enable( id );
  38311. enabled[ id ] = true;
  38312. }
  38313. }
  38314. /**
  38315. * Disables the given WebGL capability.
  38316. *
  38317. * This method caches the capability state so
  38318. * `gl.disable()` is only called when necessary.
  38319. *
  38320. * @param {GLenum} id - The capability to enable.
  38321. */
  38322. disable( id ) {
  38323. const { enabled } = this;
  38324. if ( enabled[ id ] !== false ) {
  38325. this.gl.disable( id );
  38326. enabled[ id ] = false;
  38327. }
  38328. }
  38329. /**
  38330. * Specifies whether polygons are front- or back-facing
  38331. * by setting the winding orientation.
  38332. *
  38333. * This method caches the state so `gl.frontFace()` is only
  38334. * called when necessary.
  38335. *
  38336. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  38337. */
  38338. setFlipSided( flipSided ) {
  38339. if ( this.currentFlipSided !== flipSided ) {
  38340. const { gl } = this;
  38341. if ( flipSided ) {
  38342. gl.frontFace( gl.CW );
  38343. } else {
  38344. gl.frontFace( gl.CCW );
  38345. }
  38346. this.currentFlipSided = flipSided;
  38347. }
  38348. }
  38349. /**
  38350. * Specifies whether or not front- and/or back-facing
  38351. * polygons can be culled.
  38352. *
  38353. * This method caches the state so `gl.cullFace()` is only
  38354. * called when necessary.
  38355. *
  38356. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  38357. */
  38358. setCullFace( cullFace ) {
  38359. const { gl } = this;
  38360. if ( cullFace !== CullFaceNone ) {
  38361. this.enable( gl.CULL_FACE );
  38362. if ( cullFace !== this.currentCullFace ) {
  38363. if ( cullFace === CullFaceBack ) {
  38364. gl.cullFace( gl.BACK );
  38365. } else if ( cullFace === CullFaceFront ) {
  38366. gl.cullFace( gl.FRONT );
  38367. } else {
  38368. gl.cullFace( gl.FRONT_AND_BACK );
  38369. }
  38370. }
  38371. } else {
  38372. this.disable( gl.CULL_FACE );
  38373. }
  38374. this.currentCullFace = cullFace;
  38375. }
  38376. /**
  38377. * Specifies the width of line primitives.
  38378. *
  38379. * This method caches the state so `gl.lineWidth()` is only
  38380. * called when necessary.
  38381. *
  38382. * @param {Number} width - The line width.
  38383. */
  38384. setLineWidth( width ) {
  38385. const { currentLineWidth, gl } = this;
  38386. if ( width !== currentLineWidth ) {
  38387. gl.lineWidth( width );
  38388. this.currentLineWidth = width;
  38389. }
  38390. }
  38391. /**
  38392. * Defines the blending.
  38393. *
  38394. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  38395. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  38396. *
  38397. * @param {Number} blending - The blending type.
  38398. * @param {Number} blendEquation - The blending equation.
  38399. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  38400. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  38401. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  38402. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  38403. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  38404. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  38405. */
  38406. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38407. const { gl } = this;
  38408. if ( blending === NoBlending ) {
  38409. if ( this.currentBlendingEnabled === true ) {
  38410. this.disable( gl.BLEND );
  38411. this.currentBlendingEnabled = false;
  38412. }
  38413. return;
  38414. }
  38415. if ( this.currentBlendingEnabled === false ) {
  38416. this.enable( gl.BLEND );
  38417. this.currentBlendingEnabled = true;
  38418. }
  38419. if ( blending !== CustomBlending ) {
  38420. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38421. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38422. gl.blendEquation( gl.FUNC_ADD );
  38423. this.currentBlendEquation = AddEquation;
  38424. this.currentBlendEquationAlpha = AddEquation;
  38425. }
  38426. if ( premultipliedAlpha ) {
  38427. switch ( blending ) {
  38428. case NormalBlending:
  38429. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38430. break;
  38431. case AdditiveBlending:
  38432. gl.blendFunc( gl.ONE, gl.ONE );
  38433. break;
  38434. case SubtractiveBlending:
  38435. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38436. break;
  38437. case MultiplyBlending:
  38438. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38439. break;
  38440. default:
  38441. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38442. break;
  38443. }
  38444. } else {
  38445. switch ( blending ) {
  38446. case NormalBlending:
  38447. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38448. break;
  38449. case AdditiveBlending:
  38450. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38451. break;
  38452. case SubtractiveBlending:
  38453. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38454. break;
  38455. case MultiplyBlending:
  38456. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38457. break;
  38458. default:
  38459. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38460. break;
  38461. }
  38462. }
  38463. this.currentBlendSrc = null;
  38464. this.currentBlendDst = null;
  38465. this.currentBlendSrcAlpha = null;
  38466. this.currentBlendDstAlpha = null;
  38467. this.currentBlending = blending;
  38468. this.currentPremultipledAlpha = premultipliedAlpha;
  38469. }
  38470. return;
  38471. }
  38472. // custom blending
  38473. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38474. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38475. blendDstAlpha = blendDstAlpha || blendDst;
  38476. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38477. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38478. this.currentBlendEquation = blendEquation;
  38479. this.currentBlendEquationAlpha = blendEquationAlpha;
  38480. }
  38481. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38482. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38483. this.currentBlendSrc = blendSrc;
  38484. this.currentBlendDst = blendDst;
  38485. this.currentBlendSrcAlpha = blendSrcAlpha;
  38486. this.currentBlendDstAlpha = blendDstAlpha;
  38487. }
  38488. this.currentBlending = blending;
  38489. this.currentPremultipledAlpha = false;
  38490. }
  38491. /**
  38492. * Specifies whether colors can be written when rendering
  38493. * into a framebuffer or not.
  38494. *
  38495. * This method caches the state so `gl.colorMask()` is only
  38496. * called when necessary.
  38497. *
  38498. * @param {Boolean} colorMask - The color mask.
  38499. */
  38500. setColorMask( colorMask ) {
  38501. if ( this.currentColorMask !== colorMask ) {
  38502. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38503. this.currentColorMask = colorMask;
  38504. }
  38505. }
  38506. /**
  38507. * Specifies whether the depth test is enabled or not.
  38508. *
  38509. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  38510. */
  38511. setDepthTest( depthTest ) {
  38512. const { gl } = this;
  38513. if ( depthTest ) {
  38514. this.enable( gl.DEPTH_TEST );
  38515. } else {
  38516. this.disable( gl.DEPTH_TEST );
  38517. }
  38518. }
  38519. /**
  38520. * Specifies whether depth values can be written when rendering
  38521. * into a framebuffer or not.
  38522. *
  38523. * This method caches the state so `gl.depthMask()` is only
  38524. * called when necessary.
  38525. *
  38526. * @param {Boolean} depthMask - The depth mask.
  38527. */
  38528. setDepthMask( depthMask ) {
  38529. if ( this.currentDepthMask !== depthMask ) {
  38530. this.gl.depthMask( depthMask );
  38531. this.currentDepthMask = depthMask;
  38532. }
  38533. }
  38534. /**
  38535. * Specifies the depth compare function.
  38536. *
  38537. * This method caches the state so `gl.depthFunc()` is only
  38538. * called when necessary.
  38539. *
  38540. * @param {Number} depthFunc - The depth compare function.
  38541. */
  38542. setDepthFunc( depthFunc ) {
  38543. if ( this.currentDepthFunc !== depthFunc ) {
  38544. const { gl } = this;
  38545. switch ( depthFunc ) {
  38546. case NeverDepth:
  38547. gl.depthFunc( gl.NEVER );
  38548. break;
  38549. case AlwaysDepth:
  38550. gl.depthFunc( gl.ALWAYS );
  38551. break;
  38552. case LessDepth:
  38553. gl.depthFunc( gl.LESS );
  38554. break;
  38555. case LessEqualDepth:
  38556. gl.depthFunc( gl.LEQUAL );
  38557. break;
  38558. case EqualDepth:
  38559. gl.depthFunc( gl.EQUAL );
  38560. break;
  38561. case GreaterEqualDepth:
  38562. gl.depthFunc( gl.GEQUAL );
  38563. break;
  38564. case GreaterDepth:
  38565. gl.depthFunc( gl.GREATER );
  38566. break;
  38567. case NotEqualDepth:
  38568. gl.depthFunc( gl.NOTEQUAL );
  38569. break;
  38570. default:
  38571. gl.depthFunc( gl.LEQUAL );
  38572. }
  38573. this.currentDepthFunc = depthFunc;
  38574. }
  38575. }
  38576. /**
  38577. * Specifies the viewport.
  38578. *
  38579. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38580. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38581. * @param {Number} width - The width of the viewport.
  38582. * @param {Number} height - The height of the viewport.
  38583. *
  38584. */
  38585. scissor( x, y, width, height ) {
  38586. const scissor = this._tempVec4.set( x, y, width, height );
  38587. if ( this.currentScissor.equals( scissor ) === false ) {
  38588. const { gl } = this;
  38589. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  38590. this.currentScissor.copy( scissor );
  38591. }
  38592. }
  38593. /**
  38594. * Specifies the viewport.
  38595. *
  38596. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38597. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38598. * @param {Number} width - The width of the viewport.
  38599. * @param {Number} height - The height of the viewport.
  38600. *
  38601. */
  38602. viewport( x, y, width, height ) {
  38603. const viewport = this._tempVec4.set( x, y, width, height );
  38604. if ( this.currentViewport.equals( viewport ) === false ) {
  38605. const { gl } = this;
  38606. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  38607. this.currentViewport.copy( viewport );
  38608. }
  38609. }
  38610. /**
  38611. * Defines the scissor test.
  38612. *
  38613. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38614. */
  38615. setScissorTest( boolean ) {
  38616. const gl = this.gl;
  38617. if ( boolean ) {
  38618. gl.enable( gl.SCISSOR_TEST );
  38619. } else {
  38620. gl.disable( gl.SCISSOR_TEST );
  38621. }
  38622. }
  38623. /**
  38624. * Specifies whether the stencil test is enabled or not.
  38625. *
  38626. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  38627. */
  38628. setStencilTest( stencilTest ) {
  38629. const { gl } = this;
  38630. if ( stencilTest ) {
  38631. this.enable( gl.STENCIL_TEST );
  38632. } else {
  38633. this.disable( gl.STENCIL_TEST );
  38634. }
  38635. }
  38636. /**
  38637. * Specifies whether stencil values can be written when rendering
  38638. * into a framebuffer or not.
  38639. *
  38640. * This method caches the state so `gl.stencilMask()` is only
  38641. * called when necessary.
  38642. *
  38643. * @param {Boolean} stencilMask - The stencil mask.
  38644. */
  38645. setStencilMask( stencilMask ) {
  38646. if ( this.currentStencilMask !== stencilMask ) {
  38647. this.gl.stencilMask( stencilMask );
  38648. this.currentStencilMask = stencilMask;
  38649. }
  38650. }
  38651. /**
  38652. * Specifies whether the stencil test functions.
  38653. *
  38654. * This method caches the state so `gl.stencilFunc()` is only
  38655. * called when necessary.
  38656. *
  38657. * @param {Number} stencilFunc - The stencil compare function.
  38658. * @param {Number} stencilRef - The reference value for the stencil test.
  38659. * @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.
  38660. */
  38661. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  38662. if ( this.currentStencilFunc !== stencilFunc ||
  38663. this.currentStencilRef !== stencilRef ||
  38664. this.currentStencilFuncMask !== stencilMask ) {
  38665. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  38666. this.currentStencilFunc = stencilFunc;
  38667. this.currentStencilRef = stencilRef;
  38668. this.currentStencilFuncMask = stencilMask;
  38669. }
  38670. }
  38671. /**
  38672. * Specifies whether the stencil test operation.
  38673. *
  38674. * This method caches the state so `gl.stencilOp()` is only
  38675. * called when necessary.
  38676. *
  38677. * @param {Number} stencilFail - The function to use when the stencil test fails.
  38678. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  38679. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  38680. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  38681. */
  38682. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  38683. if ( this.currentStencilFail !== stencilFail ||
  38684. this.currentStencilZFail !== stencilZFail ||
  38685. this.currentStencilZPass !== stencilZPass ) {
  38686. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  38687. this.currentStencilFail = stencilFail;
  38688. this.currentStencilZFail = stencilZFail;
  38689. this.currentStencilZPass = stencilZPass;
  38690. }
  38691. }
  38692. /**
  38693. * Configures the WebGL state for the given material.
  38694. *
  38695. * @param {Material} material - The material to configure the state for.
  38696. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  38697. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  38698. */
  38699. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  38700. const { gl } = this;
  38701. material.side === DoubleSide
  38702. ? this.disable( gl.CULL_FACE )
  38703. : this.enable( gl.CULL_FACE );
  38704. let flipSided = ( material.side === BackSide );
  38705. if ( frontFaceCW ) flipSided = ! flipSided;
  38706. this.setFlipSided( flipSided );
  38707. ( material.blending === NormalBlending && material.transparent === false )
  38708. ? this.setBlending( NoBlending )
  38709. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  38710. this.setDepthFunc( material.depthFunc );
  38711. this.setDepthTest( material.depthTest );
  38712. this.setDepthMask( material.depthWrite );
  38713. this.setColorMask( material.colorWrite );
  38714. const stencilWrite = material.stencilWrite;
  38715. this.setStencilTest( stencilWrite );
  38716. if ( stencilWrite ) {
  38717. this.setStencilMask( material.stencilWriteMask );
  38718. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  38719. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  38720. }
  38721. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  38722. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  38723. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  38724. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  38725. if ( hardwareClippingPlanes > 0 ) {
  38726. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  38727. const CLIP_DISTANCE0_WEBGL = 0x3000;
  38728. for ( let i = 0; i < 8; i ++ ) {
  38729. if ( i < hardwareClippingPlanes ) {
  38730. this.enable( CLIP_DISTANCE0_WEBGL + i );
  38731. } else {
  38732. this.disable( CLIP_DISTANCE0_WEBGL + i );
  38733. }
  38734. }
  38735. }
  38736. }
  38737. }
  38738. /**
  38739. * Specifies the polygon offset.
  38740. *
  38741. * This method caches the state so `gl.polygonOffset()` is only
  38742. * called when necessary.
  38743. *
  38744. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  38745. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  38746. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  38747. */
  38748. setPolygonOffset( polygonOffset, factor, units ) {
  38749. const { gl } = this;
  38750. if ( polygonOffset ) {
  38751. this.enable( gl.POLYGON_OFFSET_FILL );
  38752. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  38753. gl.polygonOffset( factor, units );
  38754. this.currentPolygonOffsetFactor = factor;
  38755. this.currentPolygonOffsetUnits = units;
  38756. }
  38757. } else {
  38758. this.disable( gl.POLYGON_OFFSET_FILL );
  38759. }
  38760. }
  38761. /**
  38762. * Defines the usage of the given WebGL program.
  38763. *
  38764. * This method caches the state so `gl.useProgram()` is only
  38765. * called when necessary.
  38766. *
  38767. * @param {WebGLProgram} program - The WebGL program to use.
  38768. * @return {Boolean} Whether a program change has been executed or not.
  38769. */
  38770. useProgram( program ) {
  38771. if ( this.currentProgram !== program ) {
  38772. this.gl.useProgram( program );
  38773. this.currentProgram = program;
  38774. return true;
  38775. }
  38776. return false;
  38777. }
  38778. // framebuffer
  38779. /**
  38780. * Binds the given framebuffer.
  38781. *
  38782. * This method caches the state so `gl.bindFramebuffer()` is only
  38783. * called when necessary.
  38784. *
  38785. * @param {Number} target - The binding point (target).
  38786. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  38787. * @return {Boolean} Whether a bind has been executed or not.
  38788. */
  38789. bindFramebuffer( target, framebuffer ) {
  38790. const { gl, currentBoundFramebuffers } = this;
  38791. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  38792. gl.bindFramebuffer( target, framebuffer );
  38793. currentBoundFramebuffers[ target ] = framebuffer;
  38794. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  38795. if ( target === gl.DRAW_FRAMEBUFFER ) {
  38796. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  38797. }
  38798. if ( target === gl.FRAMEBUFFER ) {
  38799. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  38800. }
  38801. return true;
  38802. }
  38803. return false;
  38804. }
  38805. /**
  38806. * Defines draw buffers to which fragment colors are written into.
  38807. * Configures the MRT setup of custom framebuffers.
  38808. *
  38809. * This method caches the state so `gl.drawBuffers()` is only
  38810. * called when necessary.
  38811. *
  38812. * @param {RenderContext} renderContext - The render context.
  38813. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  38814. */
  38815. drawBuffers( renderContext, framebuffer ) {
  38816. const { gl } = this;
  38817. let drawBuffers = [];
  38818. let needsUpdate = false;
  38819. if ( renderContext.textures !== null ) {
  38820. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  38821. if ( drawBuffers === undefined ) {
  38822. drawBuffers = [];
  38823. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  38824. }
  38825. const textures = renderContext.textures;
  38826. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  38827. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  38828. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  38829. }
  38830. drawBuffers.length = textures.length;
  38831. needsUpdate = true;
  38832. }
  38833. } else {
  38834. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  38835. drawBuffers[ 0 ] = gl.BACK;
  38836. needsUpdate = true;
  38837. }
  38838. }
  38839. if ( needsUpdate ) {
  38840. gl.drawBuffers( drawBuffers );
  38841. }
  38842. }
  38843. // texture
  38844. /**
  38845. * Makes the given texture unit active.
  38846. *
  38847. * This method caches the state so `gl.activeTexture()` is only
  38848. * called when necessary.
  38849. *
  38850. * @param {Number} webglSlot - The texture unit to make active.
  38851. */
  38852. activeTexture( webglSlot ) {
  38853. const { gl, currentTextureSlot, maxTextures } = this;
  38854. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38855. if ( currentTextureSlot !== webglSlot ) {
  38856. gl.activeTexture( webglSlot );
  38857. this.currentTextureSlot = webglSlot;
  38858. }
  38859. }
  38860. /**
  38861. * Binds the given WebGL texture to a target.
  38862. *
  38863. * This method caches the state so `gl.bindTexture()` is only
  38864. * called when necessary.
  38865. *
  38866. * @param {Number} webglType - The binding point (target).
  38867. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  38868. * @param {Number} webglSlot - The texture.
  38869. */
  38870. bindTexture( webglType, webglTexture, webglSlot ) {
  38871. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  38872. if ( webglSlot === undefined ) {
  38873. if ( currentTextureSlot === null ) {
  38874. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38875. } else {
  38876. webglSlot = currentTextureSlot;
  38877. }
  38878. }
  38879. let boundTexture = currentBoundTextures[ webglSlot ];
  38880. if ( boundTexture === undefined ) {
  38881. boundTexture = { type: undefined, texture: undefined };
  38882. currentBoundTextures[ webglSlot ] = boundTexture;
  38883. }
  38884. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  38885. if ( currentTextureSlot !== webglSlot ) {
  38886. gl.activeTexture( webglSlot );
  38887. this.currentTextureSlot = webglSlot;
  38888. }
  38889. gl.bindTexture( webglType, webglTexture );
  38890. boundTexture.type = webglType;
  38891. boundTexture.texture = webglTexture;
  38892. }
  38893. }
  38894. /**
  38895. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  38896. *
  38897. * This method caches the state so `gl.bindBufferBase()` is only
  38898. * called when necessary.
  38899. *
  38900. * @param {Number} target - The target for the bind operation.
  38901. * @param {Number} index - The index of the target.
  38902. * @param {WebGLBuffer} buffer - The WebGL buffer.
  38903. * @return {Boolean} Whether a bind has been executed or not.
  38904. */
  38905. bindBufferBase( target, index, buffer ) {
  38906. const { gl } = this;
  38907. const key = `${target}-${index}`;
  38908. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  38909. gl.bindBufferBase( target, index, buffer );
  38910. this.currentBoundBufferBases[ key ] = buffer;
  38911. return true;
  38912. }
  38913. return false;
  38914. }
  38915. /**
  38916. * Unbinds the current bound texture.
  38917. *
  38918. * This method caches the state so `gl.bindTexture()` is only
  38919. * called when necessary.
  38920. */
  38921. unbindTexture() {
  38922. const { gl, currentTextureSlot, currentBoundTextures } = this;
  38923. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  38924. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  38925. gl.bindTexture( boundTexture.type, null );
  38926. boundTexture.type = undefined;
  38927. boundTexture.texture = undefined;
  38928. }
  38929. }
  38930. }
  38931. /**
  38932. * A WebGL 2 backend utility module with common helpers.
  38933. *
  38934. * @private
  38935. */
  38936. class WebGLUtils {
  38937. /**
  38938. * Constructs a new utility object.
  38939. *
  38940. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38941. */
  38942. constructor( backend ) {
  38943. /**
  38944. * A reference to the WebGL 2 backend.
  38945. *
  38946. * @type {WebGLBackend}
  38947. */
  38948. this.backend = backend;
  38949. /**
  38950. * A reference to the rendering context.
  38951. *
  38952. * @type {WebGL2RenderingContext}
  38953. */
  38954. this.gl = this.backend.gl;
  38955. /**
  38956. * A reference to a backend module holding extension-related
  38957. * utility functions.
  38958. *
  38959. * @type {WebGLExtensions}
  38960. */
  38961. this.extensions = backend.extensions;
  38962. }
  38963. /**
  38964. * Converts the given three.js constant into a WebGL constant.
  38965. * The method currently supports the conversion of texture formats
  38966. * and types.
  38967. *
  38968. * @param {Number} p - The three.js constant.
  38969. * @param {String} [colorSpace=NoColorSpace] - The color space.
  38970. * @return {Number} The corresponding WebGL constant.
  38971. */
  38972. convert( p, colorSpace = NoColorSpace ) {
  38973. const { gl, extensions } = this;
  38974. let extension;
  38975. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38976. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38977. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38978. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38979. if ( p === ByteType ) return gl.BYTE;
  38980. if ( p === ShortType ) return gl.SHORT;
  38981. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38982. if ( p === IntType ) return gl.INT;
  38983. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38984. if ( p === FloatType ) return gl.FLOAT;
  38985. if ( p === HalfFloatType ) {
  38986. return gl.HALF_FLOAT;
  38987. }
  38988. if ( p === AlphaFormat ) return gl.ALPHA;
  38989. if ( p === RGBFormat ) return gl.RGB;
  38990. if ( p === RGBAFormat ) return gl.RGBA;
  38991. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38992. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38993. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38994. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38995. // WebGL2 formats.
  38996. if ( p === RedFormat ) return gl.RED;
  38997. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38998. if ( p === RGFormat ) return gl.RG;
  38999. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39000. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39001. // S3TC
  39002. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39003. if ( colorSpace === SRGBColorSpace ) {
  39004. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39005. if ( extension !== null ) {
  39006. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39007. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39008. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39009. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39010. } else {
  39011. return null;
  39012. }
  39013. } else {
  39014. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39015. if ( extension !== null ) {
  39016. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39017. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39018. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39019. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39020. } else {
  39021. return null;
  39022. }
  39023. }
  39024. }
  39025. // PVRTC
  39026. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39027. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39028. if ( extension !== null ) {
  39029. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39030. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39031. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39032. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39033. } else {
  39034. return null;
  39035. }
  39036. }
  39037. // ETC
  39038. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39039. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39040. if ( extension !== null ) {
  39041. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39042. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39043. } else {
  39044. return null;
  39045. }
  39046. }
  39047. // ASTC
  39048. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39049. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39050. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39051. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39052. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39053. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39054. if ( extension !== null ) {
  39055. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39056. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39057. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39058. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39059. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39060. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39061. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39062. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39063. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39064. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39065. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39066. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39067. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39068. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39069. } else {
  39070. return null;
  39071. }
  39072. }
  39073. // BPTC
  39074. if ( p === RGBA_BPTC_Format ) {
  39075. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39076. if ( extension !== null ) {
  39077. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39078. } else {
  39079. return null;
  39080. }
  39081. }
  39082. // RGTC
  39083. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39084. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39085. if ( extension !== null ) {
  39086. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39087. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39088. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39089. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39090. } else {
  39091. return null;
  39092. }
  39093. }
  39094. //
  39095. if ( p === UnsignedInt248Type ) {
  39096. return gl.UNSIGNED_INT_24_8;
  39097. }
  39098. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39099. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39100. }
  39101. /**
  39102. * This method can be used to synchronize the CPU with the GPU by waiting until
  39103. * ongoing GPU commands have been completed.
  39104. *
  39105. * @private
  39106. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39107. */
  39108. _clientWaitAsync() {
  39109. const { gl } = this;
  39110. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39111. gl.flush();
  39112. return new Promise( ( resolve, reject ) => {
  39113. function test() {
  39114. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39115. if ( res === gl.WAIT_FAILED ) {
  39116. gl.deleteSync( sync );
  39117. reject();
  39118. return;
  39119. }
  39120. if ( res === gl.TIMEOUT_EXPIRED ) {
  39121. requestAnimationFrame( test );
  39122. return;
  39123. }
  39124. gl.deleteSync( sync );
  39125. resolve();
  39126. }
  39127. test();
  39128. } );
  39129. }
  39130. }
  39131. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39132. /**
  39133. * A WebGL 2 backend utility module for managing textures.
  39134. *
  39135. * @private
  39136. */
  39137. class WebGLTextureUtils {
  39138. /**
  39139. * Constructs a new utility object.
  39140. *
  39141. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39142. */
  39143. constructor( backend ) {
  39144. /**
  39145. * A reference to the WebGL 2 backend.
  39146. *
  39147. * @type {WebGLBackend}
  39148. */
  39149. this.backend = backend;
  39150. /**
  39151. * A reference to the rendering context.
  39152. *
  39153. * @type {WebGL2RenderingContext}
  39154. */
  39155. this.gl = backend.gl;
  39156. /**
  39157. * A reference to a backend module holding extension-related
  39158. * utility functions.
  39159. *
  39160. * @type {WebGLExtensions}
  39161. */
  39162. this.extensions = backend.extensions;
  39163. /**
  39164. * A dictionary for managing default textures. The key
  39165. * is the binding point (target), the value the WEbGL texture object.
  39166. *
  39167. * @type {Object<GLenum,WebGLTexture>}
  39168. */
  39169. this.defaultTextures = {};
  39170. if ( initialized === false ) {
  39171. this._init();
  39172. initialized = true;
  39173. }
  39174. }
  39175. /**
  39176. * Inits the state of the utility.
  39177. *
  39178. * @private
  39179. */
  39180. _init() {
  39181. const gl = this.gl;
  39182. // Store only WebGL constants here.
  39183. wrappingToGL = {
  39184. [ RepeatWrapping ]: gl.REPEAT,
  39185. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39186. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39187. };
  39188. filterToGL = {
  39189. [ NearestFilter ]: gl.NEAREST,
  39190. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39191. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39192. [ LinearFilter ]: gl.LINEAR,
  39193. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39194. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39195. };
  39196. compareToGL = {
  39197. [ NeverCompare ]: gl.NEVER,
  39198. [ AlwaysCompare ]: gl.ALWAYS,
  39199. [ LessCompare ]: gl.LESS,
  39200. [ LessEqualCompare ]: gl.LEQUAL,
  39201. [ EqualCompare ]: gl.EQUAL,
  39202. [ GreaterEqualCompare ]: gl.GEQUAL,
  39203. [ GreaterCompare ]: gl.GREATER,
  39204. [ NotEqualCompare ]: gl.NOTEQUAL
  39205. };
  39206. }
  39207. /**
  39208. * Returns the native texture type for the given texture.
  39209. *
  39210. * @param {Texture} texture - The texture.
  39211. * @return {GLenum} The native texture type.
  39212. */
  39213. getGLTextureType( texture ) {
  39214. const { gl } = this;
  39215. let glTextureType;
  39216. if ( texture.isCubeTexture === true ) {
  39217. glTextureType = gl.TEXTURE_CUBE_MAP;
  39218. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39219. glTextureType = gl.TEXTURE_2D_ARRAY;
  39220. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39221. glTextureType = gl.TEXTURE_3D;
  39222. } else {
  39223. glTextureType = gl.TEXTURE_2D;
  39224. }
  39225. return glTextureType;
  39226. }
  39227. /**
  39228. * Returns the native texture type for the given texture.
  39229. *
  39230. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39231. * @param {GLenum} glFormat - The WebGL format.
  39232. * @param {GLenum} glType - The WebGL type.
  39233. * @param {String} colorSpace - The texture's color space.
  39234. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39235. * @return {GLenum} The internal format.
  39236. */
  39237. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39238. const { gl, extensions } = this;
  39239. if ( internalFormatName !== null ) {
  39240. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39241. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39242. }
  39243. let internalFormat = glFormat;
  39244. if ( glFormat === gl.RED ) {
  39245. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39246. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39247. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39248. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39249. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39250. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39251. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39252. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39253. }
  39254. if ( glFormat === gl.RED_INTEGER ) {
  39255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39256. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39257. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39258. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39259. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39260. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39261. }
  39262. if ( glFormat === gl.RG ) {
  39263. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39264. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39265. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39266. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39267. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39268. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39269. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39270. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39271. }
  39272. if ( glFormat === gl.RG_INTEGER ) {
  39273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39276. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39277. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39278. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39279. }
  39280. if ( glFormat === gl.RGB ) {
  39281. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39282. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39283. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39284. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39285. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39286. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39287. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39288. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39289. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39290. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39291. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39292. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39293. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39294. }
  39295. if ( glFormat === gl.RGB_INTEGER ) {
  39296. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39297. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39298. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39299. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39300. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39301. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39302. }
  39303. if ( glFormat === gl.RGBA ) {
  39304. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39305. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39306. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39307. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39308. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39309. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39310. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39311. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39312. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39313. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39314. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39315. }
  39316. if ( glFormat === gl.RGBA_INTEGER ) {
  39317. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39318. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39319. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39320. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39321. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39322. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39323. }
  39324. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39325. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39326. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39327. }
  39328. if ( glFormat === gl.DEPTH_STENCIL ) {
  39329. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39330. }
  39331. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39332. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39333. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39334. extensions.get( 'EXT_color_buffer_float' );
  39335. }
  39336. return internalFormat;
  39337. }
  39338. /**
  39339. * Sets the texture parameters for the given texture.
  39340. *
  39341. * @param {GLenum} textureType - The texture type.
  39342. * @param {Texture} texture - The texture.
  39343. */
  39344. setTextureParameters( textureType, texture ) {
  39345. const { gl, extensions, backend } = this;
  39346. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39347. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39348. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39349. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39350. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39351. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39352. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39353. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39354. }
  39355. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39356. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  39357. // follow WebGPU backend mapping for texture filtering
  39358. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  39359. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39360. if ( texture.compareFunction ) {
  39361. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39362. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39363. }
  39364. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39365. if ( texture.magFilter === NearestFilter ) return;
  39366. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39367. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39368. if ( texture.anisotropy > 1 ) {
  39369. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39370. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39371. }
  39372. }
  39373. }
  39374. /**
  39375. * Creates a default texture for the given texture that can be used
  39376. * as a placeholder until the actual texture is ready for usage.
  39377. *
  39378. * @param {Texture} texture - The texture to create a default texture for.
  39379. */
  39380. createDefaultTexture( texture ) {
  39381. const { gl, backend, defaultTextures } = this;
  39382. const glTextureType = this.getGLTextureType( texture );
  39383. let textureGPU = defaultTextures[ glTextureType ];
  39384. if ( textureGPU === undefined ) {
  39385. textureGPU = gl.createTexture();
  39386. backend.state.bindTexture( glTextureType, textureGPU );
  39387. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39388. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39389. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39390. defaultTextures[ glTextureType ] = textureGPU;
  39391. }
  39392. backend.set( texture, {
  39393. textureGPU,
  39394. glTextureType,
  39395. isDefault: true
  39396. } );
  39397. }
  39398. /**
  39399. * Defines a texture on the GPU for the given texture object.
  39400. *
  39401. * @param {Texture} texture - The texture.
  39402. * @param {Object} [options={}] - Optional configuration parameter.
  39403. * @return {undefined}
  39404. */
  39405. createTexture( texture, options ) {
  39406. const { gl, backend } = this;
  39407. const { levels, width, height, depth } = options;
  39408. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39409. const glType = backend.utils.convert( texture.type );
  39410. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39411. const textureGPU = gl.createTexture();
  39412. const glTextureType = this.getGLTextureType( texture );
  39413. backend.state.bindTexture( glTextureType, textureGPU );
  39414. this.setTextureParameters( glTextureType, texture );
  39415. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  39416. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39417. } else if ( texture.isData3DTexture ) {
  39418. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39419. } else if ( ! texture.isVideoTexture ) {
  39420. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39421. }
  39422. backend.set( texture, {
  39423. textureGPU,
  39424. glTextureType,
  39425. glFormat,
  39426. glType,
  39427. glInternalFormat
  39428. } );
  39429. }
  39430. /**
  39431. * Uploads texture buffer data to the GPU memory.
  39432. *
  39433. * @param {WebGLBuffer} buffer - The buffer data.
  39434. * @param {Texture} texture - The texture,
  39435. */
  39436. copyBufferToTexture( buffer, texture ) {
  39437. const { gl, backend } = this;
  39438. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39439. const { width, height } = texture.source.data;
  39440. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39441. backend.state.bindTexture( glTextureType, textureGPU );
  39442. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39443. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39444. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39445. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39446. backend.state.unbindTexture();
  39447. // debug
  39448. // const framebuffer = gl.createFramebuffer();
  39449. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39450. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39451. // const readout = new Float32Array( width * height * 4 );
  39452. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39453. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39454. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39455. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39456. // console.log( readout );
  39457. }
  39458. /**
  39459. * Uploads the updated texture data to the GPU.
  39460. *
  39461. * @param {Texture} texture - The texture.
  39462. * @param {Object} [options={}] - Optional configuration parameter.
  39463. */
  39464. updateTexture( texture, options ) {
  39465. const { gl } = this;
  39466. const { width, height } = options;
  39467. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39468. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39469. return;
  39470. const getImage = ( source ) => {
  39471. if ( source.isDataTexture ) {
  39472. return source.image.data;
  39473. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  39474. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  39475. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  39476. source instanceof OffscreenCanvas ) {
  39477. return source;
  39478. }
  39479. return source.data;
  39480. };
  39481. this.backend.state.bindTexture( glTextureType, textureGPU );
  39482. this.setTextureParameters( glTextureType, texture );
  39483. if ( texture.isCompressedTexture ) {
  39484. const mipmaps = texture.mipmaps;
  39485. const image = options.image;
  39486. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39487. const mipmap = mipmaps[ i ];
  39488. if ( texture.isCompressedArrayTexture ) {
  39489. if ( texture.format !== gl.RGBA ) {
  39490. if ( glFormat !== null ) {
  39491. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  39492. } else {
  39493. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39494. }
  39495. } else {
  39496. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39497. }
  39498. } else {
  39499. if ( glFormat !== null ) {
  39500. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39501. } else {
  39502. console.warn( 'Unsupported compressed texture format' );
  39503. }
  39504. }
  39505. }
  39506. } else if ( texture.isCubeTexture ) {
  39507. const images = options.images;
  39508. for ( let i = 0; i < 6; i ++ ) {
  39509. const image = getImage( images[ i ] );
  39510. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39511. }
  39512. } else if ( texture.isDataArrayTexture ) {
  39513. const image = options.image;
  39514. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39515. } else if ( texture.isData3DTexture ) {
  39516. const image = options.image;
  39517. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39518. } else if ( texture.isVideoTexture ) {
  39519. texture.update();
  39520. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39521. } else {
  39522. const image = getImage( options.image );
  39523. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39524. }
  39525. }
  39526. /**
  39527. * Generates mipmaps for the given texture.
  39528. *
  39529. * @param {Texture} texture - The texture.
  39530. */
  39531. generateMipmaps( texture ) {
  39532. const { gl, backend } = this;
  39533. const { textureGPU, glTextureType } = backend.get( texture );
  39534. backend.state.bindTexture( glTextureType, textureGPU );
  39535. gl.generateMipmap( glTextureType );
  39536. }
  39537. /**
  39538. * Deallocates the render buffers of the given render target.
  39539. *
  39540. * @param {RenderTarget} renderTarget - The render target.
  39541. */
  39542. deallocateRenderBuffers( renderTarget ) {
  39543. const { gl, backend } = this;
  39544. // remove framebuffer reference
  39545. if ( renderTarget ) {
  39546. const renderContextData = backend.get( renderTarget );
  39547. renderContextData.renderBufferStorageSetup = undefined;
  39548. if ( renderContextData.framebuffers ) {
  39549. for ( const cacheKey in renderContextData.framebuffers ) {
  39550. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  39551. }
  39552. delete renderContextData.framebuffers;
  39553. }
  39554. if ( renderContextData.depthRenderbuffer ) {
  39555. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39556. delete renderContextData.depthRenderbuffer;
  39557. }
  39558. if ( renderContextData.stencilRenderbuffer ) {
  39559. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39560. delete renderContextData.stencilRenderbuffer;
  39561. }
  39562. if ( renderContextData.msaaFrameBuffer ) {
  39563. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39564. delete renderContextData.msaaFrameBuffer;
  39565. }
  39566. if ( renderContextData.msaaRenderbuffers ) {
  39567. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39568. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39569. }
  39570. delete renderContextData.msaaRenderbuffers;
  39571. }
  39572. }
  39573. }
  39574. /**
  39575. * Destroys the GPU data for the given texture object.
  39576. *
  39577. * @param {Texture} texture - The texture.
  39578. */
  39579. destroyTexture( texture ) {
  39580. const { gl, backend } = this;
  39581. const { textureGPU, renderTarget } = backend.get( texture );
  39582. this.deallocateRenderBuffers( renderTarget );
  39583. gl.deleteTexture( textureGPU );
  39584. backend.delete( texture );
  39585. }
  39586. /**
  39587. * Copies data of the given source texture to the given destination texture.
  39588. *
  39589. * @param {Texture} srcTexture - The source texture.
  39590. * @param {Texture} dstTexture - The destination texture.
  39591. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39592. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39593. * @param {Number} [level=0] - The mip level to copy.
  39594. */
  39595. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39596. const { gl, backend } = this;
  39597. const { state } = this.backend;
  39598. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39599. let width, height, minX, minY;
  39600. let dstX, dstY;
  39601. if ( srcRegion !== null ) {
  39602. width = srcRegion.max.x - srcRegion.min.x;
  39603. height = srcRegion.max.y - srcRegion.min.y;
  39604. minX = srcRegion.min.x;
  39605. minY = srcRegion.min.y;
  39606. } else {
  39607. width = srcTexture.image.width;
  39608. height = srcTexture.image.height;
  39609. minX = 0;
  39610. minY = 0;
  39611. }
  39612. if ( dstPosition !== null ) {
  39613. dstX = dstPosition.x;
  39614. dstY = dstPosition.y;
  39615. } else {
  39616. dstX = 0;
  39617. dstY = 0;
  39618. }
  39619. state.bindTexture( glTextureType, dstTextureGPU );
  39620. // As another texture upload may have changed pixelStorei
  39621. // parameters, make sure they are correct for the dstTexture
  39622. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39623. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39624. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39625. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39626. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39627. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39628. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39629. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39630. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39631. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39632. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39633. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39634. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39635. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39636. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  39637. const srcTextureData = backend.get( srcTexture );
  39638. const dstTextureData = backend.get( dstTexture );
  39639. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  39640. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  39641. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  39642. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  39643. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  39644. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  39645. let mask = gl.COLOR_BUFFER_BIT;
  39646. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  39647. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  39648. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  39649. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  39650. } else {
  39651. if ( srcTexture.isDataTexture ) {
  39652. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39653. } else {
  39654. if ( srcTexture.isCompressedTexture ) {
  39655. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39656. } else {
  39657. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39658. }
  39659. }
  39660. }
  39661. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39662. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39663. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39664. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39665. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39666. // Generate mipmaps only when copying level 0
  39667. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39668. state.unbindTexture();
  39669. }
  39670. /**
  39671. * Copies the current bound framebuffer to the given texture.
  39672. *
  39673. * @param {Texture} texture - The destination texture.
  39674. * @param {RenderContext} renderContext - The render context.
  39675. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39676. */
  39677. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39678. const { gl } = this;
  39679. const { state } = this.backend;
  39680. const { textureGPU } = this.backend.get( texture );
  39681. const { x, y, z: width, w: height } = rectangle;
  39682. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39683. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  39684. if ( requireDrawFrameBuffer ) {
  39685. const partial = ( x !== 0 || y !== 0 );
  39686. let mask;
  39687. let attachment;
  39688. if ( texture.isDepthTexture === true ) {
  39689. mask = gl.DEPTH_BUFFER_BIT;
  39690. attachment = gl.DEPTH_ATTACHMENT;
  39691. if ( renderContext.stencil ) {
  39692. mask |= gl.STENCIL_BUFFER_BIT;
  39693. }
  39694. } else {
  39695. mask = gl.COLOR_BUFFER_BIT;
  39696. attachment = gl.COLOR_ATTACHMENT0;
  39697. }
  39698. if ( partial ) {
  39699. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  39700. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  39701. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39702. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39703. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39704. const flippedY = srcHeight - y - height;
  39705. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  39706. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39707. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39708. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  39709. state.unbindTexture();
  39710. } else {
  39711. const fb = gl.createFramebuffer();
  39712. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39713. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39714. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39715. gl.deleteFramebuffer( fb );
  39716. }
  39717. } else {
  39718. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39719. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  39720. state.unbindTexture();
  39721. }
  39722. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39723. this.backend._setFramebuffer( renderContext );
  39724. }
  39725. /**
  39726. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  39727. *
  39728. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  39729. * @param {RenderContext} renderContext - The render context.
  39730. */
  39731. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39732. const { gl } = this;
  39733. const renderTarget = renderContext.renderTarget;
  39734. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39735. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39736. if ( depthBuffer && ! stencilBuffer ) {
  39737. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39738. if ( samples > 0 ) {
  39739. if ( depthTexture && depthTexture.isDepthTexture ) {
  39740. if ( depthTexture.type === gl.FLOAT ) {
  39741. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39742. }
  39743. }
  39744. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39745. } else {
  39746. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39747. }
  39748. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39749. } else if ( depthBuffer && stencilBuffer ) {
  39750. if ( samples > 0 ) {
  39751. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39752. } else {
  39753. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39754. }
  39755. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39756. }
  39757. }
  39758. /**
  39759. * Returns texture data as a typed array.
  39760. *
  39761. * @async
  39762. * @param {Texture} texture - The texture to copy.
  39763. * @param {Number} x - The x coordinate of the copy origin.
  39764. * @param {Number} y - The y coordinate of the copy origin.
  39765. * @param {Number} width - The width of the copy.
  39766. * @param {Number} height - The height of the copy.
  39767. * @param {Number} faceIndex - The face index.
  39768. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39769. */
  39770. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  39771. const { backend, gl } = this;
  39772. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  39773. const fb = gl.createFramebuffer();
  39774. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39775. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  39776. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  39777. const typedArrayType = this._getTypedArrayType( glType );
  39778. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  39779. const elementCount = width * height;
  39780. const byteLength = elementCount * bytesPerTexel;
  39781. const buffer = gl.createBuffer();
  39782. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39783. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  39784. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  39785. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39786. await backend.utils._clientWaitAsync();
  39787. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  39788. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39789. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  39790. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39791. gl.deleteFramebuffer( fb );
  39792. return dstBuffer;
  39793. }
  39794. /**
  39795. * Returns the corresponding typed array type for the given WebGL data type.
  39796. *
  39797. * @private
  39798. * @param {GLenum} glType - The WebGL data type.
  39799. * @return {TypedArray.constructor} The typed array type.
  39800. */
  39801. _getTypedArrayType( glType ) {
  39802. const { gl } = this;
  39803. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  39804. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  39805. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  39806. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  39807. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  39808. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  39809. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  39810. if ( glType === gl.FLOAT ) return Float32Array;
  39811. throw new Error( `Unsupported WebGL type: ${glType}` );
  39812. }
  39813. /**
  39814. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  39815. *
  39816. * @private
  39817. * @param {GLenum} glType - The WebGL data type.
  39818. * @param {GLenum} glFormat - The WebGL texture format.
  39819. * @return {Number} The bytes-per-texel.
  39820. */
  39821. _getBytesPerTexel( glType, glFormat ) {
  39822. const { gl } = this;
  39823. let bytesPerComponent = 0;
  39824. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  39825. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  39826. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  39827. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  39828. glType === gl.UNSIGNED_SHORT ||
  39829. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  39830. if ( glType === gl.UNSIGNED_INT ||
  39831. glType === gl.FLOAT ) bytesPerComponent = 4;
  39832. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  39833. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  39834. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  39835. }
  39836. }
  39837. /**
  39838. * A WebGL 2 backend utility module for managing extensions.
  39839. *
  39840. * @private
  39841. */
  39842. class WebGLExtensions {
  39843. /**
  39844. * Constructs a new utility object.
  39845. *
  39846. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39847. */
  39848. constructor( backend ) {
  39849. /**
  39850. * A reference to the WebGL 2 backend.
  39851. *
  39852. * @type {WebGLBackend}
  39853. */
  39854. this.backend = backend;
  39855. /**
  39856. * A reference to the rendering context.
  39857. *
  39858. * @type {WebGL2RenderingContext}
  39859. */
  39860. this.gl = this.backend.gl;
  39861. /**
  39862. * A list with all the supported WebGL extensions.
  39863. *
  39864. * @type {Array<String>}
  39865. */
  39866. this.availableExtensions = this.gl.getSupportedExtensions();
  39867. /**
  39868. * A dictionary with requested WebGL extensions.
  39869. * The key is the name of the extension, the value
  39870. * the requested extension object.
  39871. *
  39872. * @type {Object<String,Object>}
  39873. */
  39874. this.extensions = {};
  39875. }
  39876. /**
  39877. * Returns the extension object for the given extension name.
  39878. *
  39879. * @param {String} name - The extension name.
  39880. * @return {Object} The extension object.
  39881. */
  39882. get( name ) {
  39883. let extension = this.extensions[ name ];
  39884. if ( extension === undefined ) {
  39885. extension = this.gl.getExtension( name );
  39886. this.extensions[ name ] = extension;
  39887. }
  39888. return extension;
  39889. }
  39890. /**
  39891. * Returns `true` if the requested extension is available.
  39892. *
  39893. * @param {String} name - The extension name.
  39894. * @return {Boolean} Whether the given extension is available or not.
  39895. */
  39896. has( name ) {
  39897. return this.availableExtensions.includes( name );
  39898. }
  39899. }
  39900. /**
  39901. * A WebGL 2 backend utility module for managing the device's capabilities.
  39902. *
  39903. * @private
  39904. */
  39905. class WebGLCapabilities {
  39906. /**
  39907. * Constructs a new utility object.
  39908. *
  39909. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39910. */
  39911. constructor( backend ) {
  39912. /**
  39913. * A reference to the WebGL 2 backend.
  39914. *
  39915. * @type {WebGLBackend}
  39916. */
  39917. this.backend = backend;
  39918. /**
  39919. * This value holds the cached max anisotropy value.
  39920. *
  39921. * @type {Number?}
  39922. * @default null
  39923. */
  39924. this.maxAnisotropy = null;
  39925. }
  39926. /**
  39927. * Returns the maximum anisotropy texture filtering value. This value
  39928. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  39929. * WebGL extension.
  39930. *
  39931. * @return {Number} The maximum anisotropy texture filtering value.
  39932. */
  39933. getMaxAnisotropy() {
  39934. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  39935. const gl = this.backend.gl;
  39936. const extensions = this.backend.extensions;
  39937. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39938. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39939. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  39940. } else {
  39941. this.maxAnisotropy = 0;
  39942. }
  39943. return this.maxAnisotropy;
  39944. }
  39945. }
  39946. const GLFeatureName = {
  39947. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  39948. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  39949. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  39950. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  39951. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39952. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39953. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  39954. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  39955. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  39956. };
  39957. class WebGLBufferRenderer {
  39958. constructor( backend ) {
  39959. this.gl = backend.gl;
  39960. this.extensions = backend.extensions;
  39961. this.info = backend.renderer.info;
  39962. this.mode = null;
  39963. this.index = 0;
  39964. this.type = null;
  39965. this.object = null;
  39966. }
  39967. render( start, count ) {
  39968. const { gl, mode, object, type, info, index } = this;
  39969. if ( index !== 0 ) {
  39970. gl.drawElements( mode, count, type, start );
  39971. } else {
  39972. gl.drawArrays( mode, start, count );
  39973. }
  39974. info.update( object, count, mode, 1 );
  39975. }
  39976. renderInstances( start, count, primcount ) {
  39977. const { gl, mode, type, index, object, info } = this;
  39978. if ( primcount === 0 ) return;
  39979. if ( index !== 0 ) {
  39980. gl.drawElementsInstanced( mode, count, type, start, primcount );
  39981. } else {
  39982. gl.drawArraysInstanced( mode, start, count, primcount );
  39983. }
  39984. info.update( object, count, mode, primcount );
  39985. }
  39986. renderMultiDraw( starts, counts, drawCount ) {
  39987. const { extensions, mode, object, info } = this;
  39988. if ( drawCount === 0 ) return;
  39989. const extension = extensions.get( 'WEBGL_multi_draw' );
  39990. if ( extension === null ) {
  39991. for ( let i = 0; i < drawCount; i ++ ) {
  39992. this.render( starts[ i ], counts[ i ] );
  39993. }
  39994. } else {
  39995. if ( this.index !== 0 ) {
  39996. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  39997. } else {
  39998. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  39999. }
  40000. let elementCount = 0;
  40001. for ( let i = 0; i < drawCount; i ++ ) {
  40002. elementCount += counts[ i ];
  40003. }
  40004. info.update( object, elementCount, mode, 1 );
  40005. }
  40006. }
  40007. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40008. const { extensions, mode, object, info } = this;
  40009. if ( drawCount === 0 ) return;
  40010. const extension = extensions.get( 'WEBGL_multi_draw' );
  40011. if ( extension === null ) {
  40012. for ( let i = 0; i < drawCount; i ++ ) {
  40013. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40014. }
  40015. } else {
  40016. if ( this.index !== 0 ) {
  40017. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40018. } else {
  40019. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40020. }
  40021. let elementCount = 0;
  40022. for ( let i = 0; i < drawCount; i ++ ) {
  40023. elementCount += counts[ i ] * primcount[ i ];
  40024. }
  40025. info.update( object, elementCount, mode, 1 );
  40026. }
  40027. }
  40028. //
  40029. }
  40030. /**
  40031. * A backend implementation targeting WebGL 2.
  40032. *
  40033. * @private
  40034. * @augments Backend
  40035. */
  40036. class WebGLBackend extends Backend {
  40037. /**
  40038. * Constructs a new WebGPU backend.
  40039. *
  40040. * @param {Object} parameters - The configuration parameter.
  40041. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40042. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40043. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40044. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40045. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40046. * @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.
  40047. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40048. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  40049. */
  40050. constructor( parameters = {} ) {
  40051. super( parameters );
  40052. /**
  40053. * This flag can be used for type testing.
  40054. *
  40055. * @type {Boolean}
  40056. * @readonly
  40057. * @default true
  40058. */
  40059. this.isWebGLBackend = true;
  40060. /**
  40061. * A reference to a backend module holding shader attribute-related
  40062. * utility functions.
  40063. *
  40064. * @type {WebGLAttributeUtils?}
  40065. * @default null
  40066. */
  40067. this.attributeUtils = null;
  40068. /**
  40069. * A reference to a backend module holding extension-related
  40070. * utility functions.
  40071. *
  40072. * @type {WebGLExtensions?}
  40073. * @default null
  40074. */
  40075. this.extensions = null;
  40076. /**
  40077. * A reference to a backend module holding capability-related
  40078. * utility functions.
  40079. *
  40080. * @type {WebGLCapabilities?}
  40081. * @default null
  40082. */
  40083. this.capabilities = null;
  40084. /**
  40085. * A reference to a backend module holding texture-related
  40086. * utility functions.
  40087. *
  40088. * @type {WebGLTextureUtils?}
  40089. * @default null
  40090. */
  40091. this.textureUtils = null;
  40092. /**
  40093. * A reference to a backend module holding renderer-related
  40094. * utility functions.
  40095. *
  40096. * @type {WebGLBufferRenderer?}
  40097. * @default null
  40098. */
  40099. this.bufferRenderer = null;
  40100. /**
  40101. * A reference to the rendering context.
  40102. *
  40103. * @type {WebGL2RenderingContext?}
  40104. * @default null
  40105. */
  40106. this.gl = null;
  40107. /**
  40108. * A reference to a backend module holding state-related
  40109. * utility functions.
  40110. *
  40111. * @type {WebGLState?}
  40112. * @default null
  40113. */
  40114. this.state = null;
  40115. /**
  40116. * A reference to a backend module holding common
  40117. * utility functions.
  40118. *
  40119. * @type {WebGLUtils?}
  40120. * @default null
  40121. */
  40122. this.utils = null;
  40123. /**
  40124. * Dictionary for caching VAOs.
  40125. *
  40126. * @type {Object<String,WebGLVertexArrayObject>}
  40127. */
  40128. this.vaoCache = {};
  40129. /**
  40130. * Dictionary for caching transform feedback objects.
  40131. *
  40132. * @type {Object<String,WebGLTransformFeedback>}
  40133. */
  40134. this.transformFeedbackCache = {};
  40135. /**
  40136. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  40137. * Only relevant when using compute shaders.
  40138. *
  40139. * @type {Boolean}
  40140. * @default false
  40141. */
  40142. this.discard = false;
  40143. /**
  40144. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  40145. * device does not support the extension.
  40146. *
  40147. * @type {EXTDisjointTimerQueryWebGL2?}
  40148. * @default null
  40149. */
  40150. this.disjoint = null;
  40151. /**
  40152. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  40153. * device does not support the extension.
  40154. *
  40155. * @type {KHRParallelShaderCompile?}
  40156. * @default null
  40157. */
  40158. this.parallel = null;
  40159. /**
  40160. * Whether to track timestamps with a Timestamp Query API or not.
  40161. *
  40162. * @type {Boolean}
  40163. * @default false
  40164. */
  40165. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40166. /**
  40167. * A reference to the current render context.
  40168. *
  40169. * @private
  40170. * @type {RenderContext}
  40171. * @default null
  40172. */
  40173. this._currentContext = null;
  40174. /**
  40175. * A unique collection of bindings.
  40176. *
  40177. * @private
  40178. * @type {WeakSet}
  40179. */
  40180. this._knownBindings = new WeakSet();
  40181. /**
  40182. * The target framebuffer when rendering with
  40183. * the WebXR device API.
  40184. *
  40185. * @private
  40186. * @type {WebGLFramebuffer}
  40187. * @default null
  40188. */
  40189. this._xrFamebuffer = null;
  40190. }
  40191. /**
  40192. * Initializes the backend so it is ready for usage.
  40193. *
  40194. * @param {Renderer} renderer - The renderer.
  40195. */
  40196. init( renderer ) {
  40197. super.init( renderer );
  40198. //
  40199. const parameters = this.parameters;
  40200. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40201. function onContextLost( event ) {
  40202. event.preventDefault();
  40203. const contextLossInfo = {
  40204. api: 'WebGL',
  40205. message: event.statusMessage || 'Unknown reason',
  40206. reason: null,
  40207. originalEvent: event
  40208. };
  40209. renderer.onDeviceLost( contextLossInfo );
  40210. }
  40211. this._onContextLost = onContextLost;
  40212. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40213. this.gl = glContext;
  40214. this.extensions = new WebGLExtensions( this );
  40215. this.capabilities = new WebGLCapabilities( this );
  40216. this.attributeUtils = new WebGLAttributeUtils( this );
  40217. this.textureUtils = new WebGLTextureUtils( this );
  40218. this.bufferRenderer = new WebGLBufferRenderer( this );
  40219. this.state = new WebGLState( this );
  40220. this.utils = new WebGLUtils( this );
  40221. this.extensions.get( 'EXT_color_buffer_float' );
  40222. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40223. this.extensions.get( 'OES_texture_float_linear' );
  40224. this.extensions.get( 'EXT_color_buffer_half_float' );
  40225. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40226. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40227. this.extensions.get( 'WEBGL_multi_draw' );
  40228. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40229. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40230. }
  40231. /**
  40232. * The coordinate system of the backend.
  40233. *
  40234. * @type {Number}
  40235. * @readonly
  40236. */
  40237. get coordinateSystem() {
  40238. return WebGLCoordinateSystem;
  40239. }
  40240. /**
  40241. * This method performs a readback operation by moving buffer data from
  40242. * a storage buffer attribute from the GPU to the CPU.
  40243. *
  40244. * @async
  40245. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40246. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40247. */
  40248. async getArrayBufferAsync( attribute ) {
  40249. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40250. }
  40251. /**
  40252. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40253. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40254. *
  40255. * @async
  40256. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40257. */
  40258. async waitForGPU() {
  40259. await this.utils._clientWaitAsync();
  40260. }
  40261. /**
  40262. * Ensures the backend is XR compatible.
  40263. *
  40264. * @async
  40265. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  40266. */
  40267. async makeXRCompatible() {
  40268. const attributes = this.gl.getContextAttributes();
  40269. if ( attributes.xrCompatible !== true ) {
  40270. await this.gl.makeXRCompatible();
  40271. }
  40272. }
  40273. /**
  40274. * Sets the XR rendering destination.
  40275. *
  40276. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  40277. */
  40278. setXRTarget( xrFamebuffer ) {
  40279. this._xrFamebuffer = xrFamebuffer;
  40280. }
  40281. /**
  40282. * Inits a time stamp query for the given render context.
  40283. *
  40284. * @param {RenderContext} renderContext - The render context.
  40285. */
  40286. initTimestampQuery( renderContext ) {
  40287. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40288. const renderContextData = this.get( renderContext );
  40289. if ( this.queryRunning ) {
  40290. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40291. renderContextData.queryQueue.push( renderContext );
  40292. return;
  40293. }
  40294. if ( renderContextData.activeQuery ) {
  40295. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40296. renderContextData.activeQuery = null;
  40297. }
  40298. renderContextData.activeQuery = this.gl.createQuery();
  40299. if ( renderContextData.activeQuery !== null ) {
  40300. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40301. this.queryRunning = true;
  40302. }
  40303. }
  40304. // timestamp utils
  40305. /**
  40306. * Prepares the timestamp buffer.
  40307. *
  40308. * @param {RenderContext} renderContext - The render context.
  40309. */
  40310. prepareTimestampBuffer( renderContext ) {
  40311. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40312. const renderContextData = this.get( renderContext );
  40313. if ( renderContextData.activeQuery ) {
  40314. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40315. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40316. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40317. renderContextData.activeQuery = null;
  40318. this.queryRunning = false;
  40319. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40320. const nextRenderContext = renderContextData.queryQueue.shift();
  40321. this.initTimestampQuery( nextRenderContext );
  40322. }
  40323. }
  40324. }
  40325. /**
  40326. * Resolves the time stamp for the given render context and type.
  40327. *
  40328. * @async
  40329. * @param {RenderContext} renderContext - The render context.
  40330. * @param {String} type - The render context.
  40331. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  40332. */
  40333. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40334. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40335. const renderContextData = this.get( renderContext );
  40336. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40337. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40338. const queryInfo = renderContextData.gpuQueries[ i ];
  40339. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40340. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40341. if ( available && ! disjoint ) {
  40342. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40343. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40344. this.gl.deleteQuery( queryInfo.query );
  40345. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40346. i --;
  40347. this.renderer.info.updateTimestamp( type, duration );
  40348. }
  40349. }
  40350. }
  40351. /**
  40352. * Returns the backend's rendering context.
  40353. *
  40354. * @return {WebGL2RenderingContext} The rendering context.
  40355. */
  40356. getContext() {
  40357. return this.gl;
  40358. }
  40359. /**
  40360. * This method is executed at the beginning of a render call and prepares
  40361. * the WebGL state for upcoming render calls
  40362. *
  40363. * @param {RenderContext} renderContext - The render context.
  40364. */
  40365. beginRender( renderContext ) {
  40366. const { state, gl } = this;
  40367. const renderContextData = this.get( renderContext );
  40368. //
  40369. //
  40370. this.initTimestampQuery( renderContext );
  40371. renderContextData.previousContext = this._currentContext;
  40372. this._currentContext = renderContext;
  40373. this._setFramebuffer( renderContext );
  40374. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40375. //
  40376. if ( renderContext.viewport ) {
  40377. this.updateViewport( renderContext );
  40378. } else {
  40379. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40380. }
  40381. if ( renderContext.scissor ) {
  40382. const { x, y, width, height } = renderContext.scissorValue;
  40383. state.scissor( x, renderContext.height - height - y, width, height );
  40384. }
  40385. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40386. if ( occlusionQueryCount > 0 ) {
  40387. // Get a reference to the array of objects with queries. The renderContextData property
  40388. // can be changed by another render pass before the async reading of all previous queries complete
  40389. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40390. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40391. renderContextData.lastOcclusionObject = null;
  40392. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40393. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40394. renderContextData.occlusionQueryIndex = 0;
  40395. }
  40396. }
  40397. /**
  40398. * This method is executed at the end of a render call and finalizes work
  40399. * after draw calls.
  40400. *
  40401. * @param {RenderContext} renderContext - The render context.
  40402. */
  40403. finishRender( renderContext ) {
  40404. const { gl, state } = this;
  40405. const renderContextData = this.get( renderContext );
  40406. const previousContext = renderContextData.previousContext;
  40407. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40408. if ( occlusionQueryCount > 0 ) {
  40409. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40410. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40411. }
  40412. this.resolveOccludedAsync( renderContext );
  40413. }
  40414. const textures = renderContext.textures;
  40415. if ( textures !== null ) {
  40416. for ( let i = 0; i < textures.length; i ++ ) {
  40417. const texture = textures[ i ];
  40418. if ( texture.generateMipmaps ) {
  40419. this.generateMipmaps( texture );
  40420. }
  40421. }
  40422. }
  40423. this._currentContext = previousContext;
  40424. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40425. const renderTargetContextData = this.get( renderContext.renderTarget );
  40426. const { samples } = renderContext.renderTarget;
  40427. if ( samples > 0 ) {
  40428. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40429. const mask = gl.COLOR_BUFFER_BIT;
  40430. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40431. const textures = renderContext.textures;
  40432. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40433. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40434. for ( let i = 0; i < textures.length; i ++ ) {
  40435. // TODO Add support for MRT
  40436. if ( renderContext.scissor ) {
  40437. const { x, y, width, height } = renderContext.scissorValue;
  40438. const viewY = renderContext.height - height - y;
  40439. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40440. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40441. } else {
  40442. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40443. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40444. }
  40445. }
  40446. }
  40447. }
  40448. if ( previousContext !== null ) {
  40449. this._setFramebuffer( previousContext );
  40450. if ( previousContext.viewport ) {
  40451. this.updateViewport( previousContext );
  40452. } else {
  40453. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40454. }
  40455. }
  40456. this.prepareTimestampBuffer( renderContext );
  40457. }
  40458. /**
  40459. * This method processes the result of occlusion queries and writes it
  40460. * into render context data.
  40461. *
  40462. * @async
  40463. * @param {RenderContext} renderContext - The render context.
  40464. */
  40465. resolveOccludedAsync( renderContext ) {
  40466. const renderContextData = this.get( renderContext );
  40467. // handle occlusion query results
  40468. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40469. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40470. const occluded = new WeakSet();
  40471. const { gl } = this;
  40472. renderContextData.currentOcclusionQueryObjects = null;
  40473. renderContextData.currentOcclusionQueries = null;
  40474. const check = () => {
  40475. let completed = 0;
  40476. // check all queries and requeue as appropriate
  40477. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40478. const query = currentOcclusionQueries[ i ];
  40479. if ( query === null ) continue;
  40480. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40481. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40482. currentOcclusionQueries[ i ] = null;
  40483. gl.deleteQuery( query );
  40484. completed ++;
  40485. }
  40486. }
  40487. if ( completed < currentOcclusionQueries.length ) {
  40488. requestAnimationFrame( check );
  40489. } else {
  40490. renderContextData.occluded = occluded;
  40491. }
  40492. };
  40493. check();
  40494. }
  40495. }
  40496. /**
  40497. * Returns `true` if the given 3D object is fully occluded by other
  40498. * 3D objects in the scene.
  40499. *
  40500. * @param {RenderContext} renderContext - The render context.
  40501. * @param {Object3D} object - The 3D object to test.
  40502. * @return {Boolean} Whether the 3D object is fully occluded or not.
  40503. */
  40504. isOccluded( renderContext, object ) {
  40505. const renderContextData = this.get( renderContext );
  40506. return renderContextData.occluded && renderContextData.occluded.has( object );
  40507. }
  40508. /**
  40509. * Updates the viewport with the values from the given render context.
  40510. *
  40511. * @param {RenderContext} renderContext - The render context.
  40512. */
  40513. updateViewport( renderContext ) {
  40514. const { state } = this;
  40515. const { x, y, width, height } = renderContext.viewportValue;
  40516. state.viewport( x, renderContext.height - height - y, width, height );
  40517. }
  40518. /**
  40519. * Defines the scissor test.
  40520. *
  40521. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  40522. */
  40523. setScissorTest( boolean ) {
  40524. const state = this.state;
  40525. state.setScissorTest( boolean );
  40526. }
  40527. /**
  40528. * Performs a clear operation.
  40529. *
  40530. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  40531. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  40532. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  40533. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  40534. * @param {Boolean} [setFrameBuffer=true] - TODO.
  40535. */
  40536. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40537. const { gl } = this;
  40538. if ( descriptor === null ) {
  40539. const clearColor = this.getClearColor();
  40540. // premultiply alpha
  40541. clearColor.r *= clearColor.a;
  40542. clearColor.g *= clearColor.a;
  40543. clearColor.b *= clearColor.a;
  40544. descriptor = {
  40545. textures: null,
  40546. clearColorValue: clearColor
  40547. };
  40548. }
  40549. //
  40550. let clear = 0;
  40551. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40552. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40553. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40554. if ( clear !== 0 ) {
  40555. let clearColor;
  40556. if ( descriptor.clearColorValue ) {
  40557. clearColor = descriptor.clearColorValue;
  40558. } else {
  40559. clearColor = this.getClearColor();
  40560. // premultiply alpha
  40561. clearColor.r *= clearColor.a;
  40562. clearColor.g *= clearColor.a;
  40563. clearColor.b *= clearColor.a;
  40564. }
  40565. if ( depth ) this.state.setDepthMask( true );
  40566. if ( descriptor.textures === null ) {
  40567. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40568. gl.clear( clear );
  40569. } else {
  40570. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40571. if ( color ) {
  40572. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40573. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40574. }
  40575. }
  40576. if ( depth && stencil ) {
  40577. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40578. } else if ( depth ) {
  40579. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40580. } else if ( stencil ) {
  40581. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40582. }
  40583. }
  40584. }
  40585. }
  40586. /**
  40587. * This method is executed at the beginning of a compute call and
  40588. * prepares the state for upcoming compute tasks.
  40589. *
  40590. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40591. */
  40592. beginCompute( computeGroup ) {
  40593. const { state, gl } = this;
  40594. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40595. this.initTimestampQuery( computeGroup );
  40596. }
  40597. /**
  40598. * Executes a compute command for the given compute node.
  40599. *
  40600. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40601. * @param {Node} computeNode - The compute node.
  40602. * @param {Array<BindGroup>} bindings - The bindings.
  40603. * @param {ComputePipeline} pipeline - The compute pipeline.
  40604. */
  40605. compute( computeGroup, computeNode, bindings, pipeline ) {
  40606. const { state, gl } = this;
  40607. if ( this.discard === false ) {
  40608. // required here to handle async behaviour of render.compute()
  40609. gl.enable( gl.RASTERIZER_DISCARD );
  40610. this.discard = true;
  40611. }
  40612. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40613. const vaoKey = this._getVaoKey( null, attributes );
  40614. const vaoGPU = this.vaoCache[ vaoKey ];
  40615. if ( vaoGPU === undefined ) {
  40616. this._createVao( null, attributes );
  40617. } else {
  40618. gl.bindVertexArray( vaoGPU );
  40619. }
  40620. state.useProgram( programGPU );
  40621. this._bindUniforms( bindings );
  40622. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40623. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40624. gl.beginTransformFeedback( gl.POINTS );
  40625. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40626. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40627. } else {
  40628. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40629. }
  40630. gl.endTransformFeedback();
  40631. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40632. // switch active buffers
  40633. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40634. const dualAttributeData = transformBuffers[ i ];
  40635. if ( dualAttributeData.pbo ) {
  40636. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40637. }
  40638. dualAttributeData.switchBuffers();
  40639. }
  40640. }
  40641. /**
  40642. * This method is executed at the end of a compute call and
  40643. * finalizes work after compute tasks.
  40644. *
  40645. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40646. */
  40647. finishCompute( computeGroup ) {
  40648. const gl = this.gl;
  40649. this.discard = false;
  40650. gl.disable( gl.RASTERIZER_DISCARD );
  40651. this.prepareTimestampBuffer( computeGroup );
  40652. if ( this._currentContext ) {
  40653. this._setFramebuffer( this._currentContext );
  40654. }
  40655. }
  40656. /**
  40657. * Executes a draw command for the given render object.
  40658. *
  40659. * @param {RenderObject} renderObject - The render object to draw.
  40660. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40661. */
  40662. draw( renderObject/*, info*/ ) {
  40663. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  40664. const { programGPU } = this.get( pipeline );
  40665. const { gl, state } = this;
  40666. const contextData = this.get( context );
  40667. const drawParams = renderObject.getDrawParameters();
  40668. if ( drawParams === null ) return;
  40669. //
  40670. this._bindUniforms( renderObject.getBindings() );
  40671. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40672. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  40673. state.useProgram( programGPU );
  40674. //
  40675. const renderObjectData = this.get( renderObject );
  40676. let vaoGPU = renderObjectData.staticVao;
  40677. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  40678. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40679. vaoGPU = this.vaoCache[ vaoKey ];
  40680. if ( vaoGPU === undefined ) {
  40681. let staticVao;
  40682. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40683. if ( staticVao ) {
  40684. renderObjectData.staticVao = vaoGPU;
  40685. renderObjectData.geometryId = renderObject.geometry.id;
  40686. }
  40687. }
  40688. }
  40689. gl.bindVertexArray( vaoGPU );
  40690. //
  40691. const index = renderObject.getIndex();
  40692. //
  40693. const lastObject = contextData.lastOcclusionObject;
  40694. if ( lastObject !== object && lastObject !== undefined ) {
  40695. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40696. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40697. contextData.occlusionQueryIndex ++;
  40698. }
  40699. if ( object.occlusionTest === true ) {
  40700. const query = gl.createQuery();
  40701. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40702. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40703. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40704. }
  40705. contextData.lastOcclusionObject = object;
  40706. }
  40707. //
  40708. const renderer = this.bufferRenderer;
  40709. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40710. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40711. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40712. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40713. else {
  40714. if ( material.wireframe === true ) {
  40715. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40716. renderer.mode = gl.LINES;
  40717. } else {
  40718. renderer.mode = gl.TRIANGLES;
  40719. }
  40720. }
  40721. //
  40722. const { vertexCount, instanceCount } = drawParams;
  40723. let { firstVertex } = drawParams;
  40724. renderer.object = object;
  40725. if ( index !== null ) {
  40726. firstVertex *= index.array.BYTES_PER_ELEMENT;
  40727. const indexData = this.get( index );
  40728. renderer.index = index.count;
  40729. renderer.type = indexData.type;
  40730. } else {
  40731. renderer.index = 0;
  40732. }
  40733. const draw = () => {
  40734. if ( object.isBatchedMesh ) {
  40735. if ( object._multiDrawInstances !== null ) {
  40736. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40737. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40738. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40739. } else {
  40740. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40741. }
  40742. } else if ( instanceCount > 1 ) {
  40743. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  40744. } else {
  40745. renderer.render( firstVertex, vertexCount );
  40746. }
  40747. };
  40748. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  40749. const cameraData = this.get( renderObject.camera );
  40750. const cameras = renderObject.camera.cameras;
  40751. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  40752. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  40753. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  40754. const indexesGPU = [];
  40755. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40756. const bufferGPU = gl.createBuffer();
  40757. data[ 0 ] = i;
  40758. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40759. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  40760. indexesGPU.push( bufferGPU );
  40761. }
  40762. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  40763. }
  40764. const cameraIndexData = this.get( cameraIndex );
  40765. const pixelRatio = this.renderer.getPixelRatio();
  40766. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40767. const subCamera = cameras[ i ];
  40768. if ( object.layers.test( subCamera.layers ) ) {
  40769. const vp = subCamera.viewport;
  40770. const x = vp.x * pixelRatio;
  40771. const y = vp.y * pixelRatio;
  40772. const width = vp.width * pixelRatio;
  40773. const height = vp.height * pixelRatio;
  40774. state.viewport(
  40775. Math.floor( x ),
  40776. Math.floor( renderObject.context.height - height - y ),
  40777. Math.floor( width ),
  40778. Math.floor( height )
  40779. );
  40780. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  40781. draw();
  40782. }
  40783. }
  40784. } else {
  40785. draw();
  40786. }
  40787. //
  40788. gl.bindVertexArray( null );
  40789. }
  40790. /**
  40791. * Explain why always null is returned.
  40792. *
  40793. * @param {RenderObject} renderObject - The render object.
  40794. * @return {Boolean} Whether the render pipeline requires an update or not.
  40795. */
  40796. needsRenderUpdate( /*renderObject*/ ) {
  40797. return false;
  40798. }
  40799. /**
  40800. * Explain why no cache key is computed.
  40801. *
  40802. * @param {RenderObject} renderObject - The render object.
  40803. * @return {String} The cache key.
  40804. */
  40805. getRenderCacheKey( /*renderObject*/ ) {
  40806. return '';
  40807. }
  40808. // textures
  40809. /**
  40810. * Creates a default texture for the given texture that can be used
  40811. * as a placeholder until the actual texture is ready for usage.
  40812. *
  40813. * @param {Texture} texture - The texture to create a default texture for.
  40814. */
  40815. createDefaultTexture( texture ) {
  40816. this.textureUtils.createDefaultTexture( texture );
  40817. }
  40818. /**
  40819. * Defines a texture on the GPU for the given texture object.
  40820. *
  40821. * @param {Texture} texture - The texture.
  40822. * @param {Object} [options={}] - Optional configuration parameter.
  40823. */
  40824. createTexture( texture, options ) {
  40825. this.textureUtils.createTexture( texture, options );
  40826. }
  40827. /**
  40828. * Uploads the updated texture data to the GPU.
  40829. *
  40830. * @param {Texture} texture - The texture.
  40831. * @param {Object} [options={}] - Optional configuration parameter.
  40832. */
  40833. updateTexture( texture, options ) {
  40834. this.textureUtils.updateTexture( texture, options );
  40835. }
  40836. /**
  40837. * Generates mipmaps for the given texture.
  40838. *
  40839. * @param {Texture} texture - The texture.
  40840. */
  40841. generateMipmaps( texture ) {
  40842. this.textureUtils.generateMipmaps( texture );
  40843. }
  40844. /**
  40845. * Destroys the GPU data for the given texture object.
  40846. *
  40847. * @param {Texture} texture - The texture.
  40848. */
  40849. destroyTexture( texture ) {
  40850. this.textureUtils.destroyTexture( texture );
  40851. }
  40852. /**
  40853. * Returns texture data as a typed array.
  40854. *
  40855. * @async
  40856. * @param {Texture} texture - The texture to copy.
  40857. * @param {Number} x - The x coordinate of the copy origin.
  40858. * @param {Number} y - The y coordinate of the copy origin.
  40859. * @param {Number} width - The width of the copy.
  40860. * @param {Number} height - The height of the copy.
  40861. * @param {Number} faceIndex - The face index.
  40862. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40863. */
  40864. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40865. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  40866. }
  40867. /**
  40868. * This method does nothing since WebGL 2 has no concept of samplers.
  40869. *
  40870. * @param {Texture} texture - The texture to create the sampler for.
  40871. */
  40872. createSampler( /*texture*/ ) {
  40873. //console.warn( 'Abstract class.' );
  40874. }
  40875. /**
  40876. * This method does nothing since WebGL 2 has no concept of samplers.
  40877. *
  40878. * @param {Texture} texture - The texture to destroy the sampler for.
  40879. */
  40880. destroySampler( /*texture*/ ) {}
  40881. // node builder
  40882. /**
  40883. * Returns a node builder for the given render object.
  40884. *
  40885. * @param {RenderObject} object - The render object.
  40886. * @param {Renderer} renderer - The renderer.
  40887. * @return {GLSLNodeBuilder} The node builder.
  40888. */
  40889. createNodeBuilder( object, renderer ) {
  40890. return new GLSLNodeBuilder( object, renderer );
  40891. }
  40892. // program
  40893. /**
  40894. * Creates a shader program from the given programmable stage.
  40895. *
  40896. * @param {ProgrammableStage} program - The programmable stage.
  40897. */
  40898. createProgram( program ) {
  40899. const gl = this.gl;
  40900. const { stage, code } = program;
  40901. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40902. gl.shaderSource( shader, code );
  40903. gl.compileShader( shader );
  40904. this.set( program, {
  40905. shaderGPU: shader
  40906. } );
  40907. }
  40908. /**
  40909. * Destroys the shader program of the given programmable stage.
  40910. *
  40911. * @param {ProgrammableStage} program - The programmable stage.
  40912. */
  40913. destroyProgram( program ) {
  40914. this.delete( program );
  40915. }
  40916. /**
  40917. * Creates a render pipeline for the given render object.
  40918. *
  40919. * @param {RenderObject} renderObject - The render object.
  40920. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40921. */
  40922. createRenderPipeline( renderObject, promises ) {
  40923. const gl = this.gl;
  40924. const pipeline = renderObject.pipeline;
  40925. // Program
  40926. const { fragmentProgram, vertexProgram } = pipeline;
  40927. const programGPU = gl.createProgram();
  40928. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40929. const vertexShader = this.get( vertexProgram ).shaderGPU;
  40930. gl.attachShader( programGPU, fragmentShader );
  40931. gl.attachShader( programGPU, vertexShader );
  40932. gl.linkProgram( programGPU );
  40933. this.set( pipeline, {
  40934. programGPU,
  40935. fragmentShader,
  40936. vertexShader
  40937. } );
  40938. if ( promises !== null && this.parallel ) {
  40939. const p = new Promise( ( resolve /*, reject*/ ) => {
  40940. const parallel = this.parallel;
  40941. const checkStatus = () => {
  40942. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  40943. this._completeCompile( renderObject, pipeline );
  40944. resolve();
  40945. } else {
  40946. requestAnimationFrame( checkStatus );
  40947. }
  40948. };
  40949. checkStatus();
  40950. } );
  40951. promises.push( p );
  40952. return;
  40953. }
  40954. this._completeCompile( renderObject, pipeline );
  40955. }
  40956. /**
  40957. * Formats the source code of error messages.
  40958. *
  40959. * @private
  40960. * @param {String} string - The code.
  40961. * @param {Number} errorLine - The error line.
  40962. * @return {String} The formatted code.
  40963. */
  40964. _handleSource( string, errorLine ) {
  40965. const lines = string.split( '\n' );
  40966. const lines2 = [];
  40967. const from = Math.max( errorLine - 6, 0 );
  40968. const to = Math.min( errorLine + 6, lines.length );
  40969. for ( let i = from; i < to; i ++ ) {
  40970. const line = i + 1;
  40971. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  40972. }
  40973. return lines2.join( '\n' );
  40974. }
  40975. /**
  40976. * Gets the shader compilation errors from the info log.
  40977. *
  40978. * @private
  40979. * @param {WebGL2RenderingContext} gl - The rendering context.
  40980. * @param {WebGLShader} shader - The WebGL shader object.
  40981. * @param {String} type - The shader type.
  40982. * @return {String} The shader errors.
  40983. */
  40984. _getShaderErrors( gl, shader, type ) {
  40985. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  40986. const errors = gl.getShaderInfoLog( shader ).trim();
  40987. if ( status && errors === '' ) return '';
  40988. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  40989. if ( errorMatches ) {
  40990. const errorLine = parseInt( errorMatches[ 1 ] );
  40991. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  40992. } else {
  40993. return errors;
  40994. }
  40995. }
  40996. /**
  40997. * Logs shader compilation errors.
  40998. *
  40999. * @private
  41000. * @param {WebGLProgram} programGPU - The WebGL program.
  41001. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  41002. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  41003. */
  41004. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41005. if ( this.renderer.debug.checkShaderErrors ) {
  41006. const gl = this.gl;
  41007. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41008. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41009. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41010. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41011. } else {
  41012. // default error reporting
  41013. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41014. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41015. console.error(
  41016. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41017. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41018. 'Program Info Log: ' + programLog + '\n' +
  41019. vertexErrors + '\n' +
  41020. fragmentErrors
  41021. );
  41022. }
  41023. } else if ( programLog !== '' ) {
  41024. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41025. }
  41026. }
  41027. }
  41028. /**
  41029. * Completes the shader program setup for the given render object.
  41030. *
  41031. * @private
  41032. * @param {RenderObject} renderObject - The render object.
  41033. * @param {RenderPipeline} pipeline - The render pipeline.
  41034. */
  41035. _completeCompile( renderObject, pipeline ) {
  41036. const { state, gl } = this;
  41037. const pipelineData = this.get( pipeline );
  41038. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41039. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41040. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41041. }
  41042. state.useProgram( programGPU );
  41043. // Bindings
  41044. const bindings = renderObject.getBindings();
  41045. this._setupBindings( bindings, programGPU );
  41046. //
  41047. this.set( pipeline, {
  41048. programGPU
  41049. } );
  41050. }
  41051. /**
  41052. * Creates a compute pipeline for the given compute node.
  41053. *
  41054. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41055. * @param {Array<BindGroup>} bindings - The bindings.
  41056. */
  41057. createComputePipeline( computePipeline, bindings ) {
  41058. const { state, gl } = this;
  41059. // Program
  41060. const fragmentProgram = {
  41061. stage: 'fragment',
  41062. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41063. };
  41064. this.createProgram( fragmentProgram );
  41065. const { computeProgram } = computePipeline;
  41066. const programGPU = gl.createProgram();
  41067. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41068. const vertexShader = this.get( computeProgram ).shaderGPU;
  41069. const transforms = computeProgram.transforms;
  41070. const transformVaryingNames = [];
  41071. const transformAttributeNodes = [];
  41072. for ( let i = 0; i < transforms.length; i ++ ) {
  41073. const transform = transforms[ i ];
  41074. transformVaryingNames.push( transform.varyingName );
  41075. transformAttributeNodes.push( transform.attributeNode );
  41076. }
  41077. gl.attachShader( programGPU, fragmentShader );
  41078. gl.attachShader( programGPU, vertexShader );
  41079. gl.transformFeedbackVaryings(
  41080. programGPU,
  41081. transformVaryingNames,
  41082. gl.SEPARATE_ATTRIBS
  41083. );
  41084. gl.linkProgram( programGPU );
  41085. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41086. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41087. }
  41088. state.useProgram( programGPU );
  41089. // Bindings
  41090. this._setupBindings( bindings, programGPU );
  41091. const attributeNodes = computeProgram.attributes;
  41092. const attributes = [];
  41093. const transformBuffers = [];
  41094. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41095. const attribute = attributeNodes[ i ].node.attribute;
  41096. attributes.push( attribute );
  41097. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41098. }
  41099. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41100. const attribute = transformAttributeNodes[ i ].attribute;
  41101. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41102. const attributeData = this.get( attribute );
  41103. transformBuffers.push( attributeData );
  41104. }
  41105. //
  41106. this.set( computePipeline, {
  41107. programGPU,
  41108. transformBuffers,
  41109. attributes
  41110. } );
  41111. }
  41112. /**
  41113. * Creates bindings from the given bind group definition.
  41114. *
  41115. * @param {BindGroup} bindGroup - The bind group.
  41116. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41117. * @param {Number} cacheIndex - The cache index.
  41118. * @param {Number} version - The version.
  41119. */
  41120. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  41121. if ( this._knownBindings.has( bindings ) === false ) {
  41122. this._knownBindings.add( bindings );
  41123. let uniformBuffers = 0;
  41124. let textures = 0;
  41125. for ( const bindGroup of bindings ) {
  41126. this.set( bindGroup, {
  41127. textures: textures,
  41128. uniformBuffers: uniformBuffers
  41129. } );
  41130. for ( const binding of bindGroup.bindings ) {
  41131. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41132. if ( binding.isSampledTexture ) textures ++;
  41133. }
  41134. }
  41135. }
  41136. this.updateBindings( bindGroup, bindings );
  41137. }
  41138. /**
  41139. * Updates the given bind group definition.
  41140. *
  41141. * @param {BindGroup} bindGroup - The bind group.
  41142. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41143. * @param {Number} cacheIndex - The cache index.
  41144. * @param {Number} version - The version.
  41145. */
  41146. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  41147. const { gl } = this;
  41148. const bindGroupData = this.get( bindGroup );
  41149. let i = bindGroupData.uniformBuffers;
  41150. let t = bindGroupData.textures;
  41151. for ( const binding of bindGroup.bindings ) {
  41152. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41153. const data = binding.buffer;
  41154. const bufferGPU = gl.createBuffer();
  41155. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41156. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41157. this.set( binding, {
  41158. index: i ++,
  41159. bufferGPU
  41160. } );
  41161. } else if ( binding.isSampledTexture ) {
  41162. const { textureGPU, glTextureType } = this.get( binding.texture );
  41163. this.set( binding, {
  41164. index: t ++,
  41165. textureGPU,
  41166. glTextureType
  41167. } );
  41168. }
  41169. }
  41170. }
  41171. /**
  41172. * Updates a buffer binding.
  41173. *
  41174. * @param {Buffer} binding - The buffer binding to update.
  41175. */
  41176. updateBinding( binding ) {
  41177. const gl = this.gl;
  41178. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41179. const bindingData = this.get( binding );
  41180. const bufferGPU = bindingData.bufferGPU;
  41181. const data = binding.buffer;
  41182. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41183. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41184. }
  41185. }
  41186. // attributes
  41187. /**
  41188. * Creates the GPU buffer of an indexed shader attribute.
  41189. *
  41190. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41191. */
  41192. createIndexAttribute( attribute ) {
  41193. const gl = this.gl;
  41194. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41195. }
  41196. /**
  41197. * Creates the GPU buffer of a shader attribute.
  41198. *
  41199. * @param {BufferAttribute} attribute - The buffer attribute.
  41200. */
  41201. createAttribute( attribute ) {
  41202. if ( this.has( attribute ) ) return;
  41203. const gl = this.gl;
  41204. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41205. }
  41206. /**
  41207. * Creates the GPU buffer of a storage attribute.
  41208. *
  41209. * @param {BufferAttribute} attribute - The buffer attribute.
  41210. */
  41211. createStorageAttribute( attribute ) {
  41212. if ( this.has( attribute ) ) return;
  41213. const gl = this.gl;
  41214. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41215. }
  41216. /**
  41217. * Updates the GPU buffer of a shader attribute.
  41218. *
  41219. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41220. */
  41221. updateAttribute( attribute ) {
  41222. this.attributeUtils.updateAttribute( attribute );
  41223. }
  41224. /**
  41225. * Destroys the GPU buffer of a shader attribute.
  41226. *
  41227. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41228. */
  41229. destroyAttribute( attribute ) {
  41230. this.attributeUtils.destroyAttribute( attribute );
  41231. }
  41232. /**
  41233. * Checks if the given feature is supported by the backend.
  41234. *
  41235. * @param {String} name - The feature's name.
  41236. * @return {Boolean} Whether the feature is supported or not.
  41237. */
  41238. hasFeature( name ) {
  41239. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41240. const extensions = this.extensions;
  41241. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41242. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41243. }
  41244. return false;
  41245. }
  41246. /**
  41247. * Returns the maximum anisotropy texture filtering value.
  41248. *
  41249. * @return {Number} The maximum anisotropy texture filtering value.
  41250. */
  41251. getMaxAnisotropy() {
  41252. return this.capabilities.getMaxAnisotropy();
  41253. }
  41254. /**
  41255. * Copies data of the given source texture to the given destination texture.
  41256. *
  41257. * @param {Texture} srcTexture - The source texture.
  41258. * @param {Texture} dstTexture - The destination texture.
  41259. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  41260. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  41261. * @param {Number} [level=0] - The mip level to copy.
  41262. */
  41263. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41264. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41265. }
  41266. /**
  41267. * Copies the current bound framebuffer to the given texture.
  41268. *
  41269. * @param {Texture} texture - The destination texture.
  41270. * @param {RenderContext} renderContext - The render context.
  41271. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41272. */
  41273. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41274. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41275. }
  41276. /**
  41277. * Configures the active framebuffer from the given render context.
  41278. *
  41279. * @private
  41280. * @param {RenderContext} descriptor - The render context.
  41281. */
  41282. _setFramebuffer( descriptor ) {
  41283. const { gl, state } = this;
  41284. let currentFrameBuffer = null;
  41285. if ( descriptor.textures !== null ) {
  41286. const renderTarget = descriptor.renderTarget;
  41287. const renderTargetContextData = this.get( renderTarget );
  41288. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41289. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41290. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  41291. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  41292. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  41293. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41294. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41295. const cacheKey = getCacheKey( descriptor );
  41296. let fb;
  41297. if ( isCube ) {
  41298. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41299. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41300. } else if ( isXRRenderTarget ) {
  41301. fb = this._xrFamebuffer;
  41302. } else {
  41303. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41304. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41305. }
  41306. if ( fb === undefined ) {
  41307. fb = gl.createFramebuffer();
  41308. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41309. const textures = descriptor.textures;
  41310. if ( isCube ) {
  41311. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41312. const { textureGPU } = this.get( textures[ 0 ] );
  41313. const cubeFace = this.renderer._activeCubeFace;
  41314. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41315. } else {
  41316. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41317. for ( let i = 0; i < textures.length; i ++ ) {
  41318. const texture = textures[ i ];
  41319. const textureData = this.get( texture );
  41320. textureData.renderTarget = descriptor.renderTarget;
  41321. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41322. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41323. if ( isRenderTarget3D || isRenderTargetArray ) {
  41324. const layer = this.renderer._activeCubeFace;
  41325. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  41326. } else {
  41327. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41328. }
  41329. }
  41330. state.drawBuffers( descriptor, fb );
  41331. }
  41332. if ( descriptor.depthTexture !== null ) {
  41333. const textureData = this.get( descriptor.depthTexture );
  41334. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41335. textureData.renderTarget = descriptor.renderTarget;
  41336. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41337. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41338. }
  41339. }
  41340. if ( samples > 0 ) {
  41341. if ( msaaFb === undefined ) {
  41342. const invalidationArray = [];
  41343. msaaFb = gl.createFramebuffer();
  41344. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41345. const msaaRenderbuffers = [];
  41346. const textures = descriptor.textures;
  41347. for ( let i = 0; i < textures.length; i ++ ) {
  41348. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41349. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41350. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41351. if ( depthBuffer ) {
  41352. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41353. invalidationArray.push( depthStyle );
  41354. }
  41355. const texture = descriptor.textures[ i ];
  41356. const textureData = this.get( texture );
  41357. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41358. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41359. }
  41360. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41361. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41362. if ( depthRenderbuffer === undefined ) {
  41363. depthRenderbuffer = gl.createRenderbuffer();
  41364. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41365. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41366. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41367. invalidationArray.push( depthStyle );
  41368. }
  41369. renderTargetContextData.invalidationArray = invalidationArray;
  41370. }
  41371. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41372. } else {
  41373. currentFrameBuffer = fb;
  41374. }
  41375. }
  41376. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41377. }
  41378. /**
  41379. * Computes the VAO key for the given index and attributes.
  41380. *
  41381. * @private
  41382. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41383. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41384. * @return {String} The VAO key.
  41385. */
  41386. _getVaoKey( index, attributes ) {
  41387. let key = '';
  41388. if ( index !== null ) {
  41389. const indexData = this.get( index );
  41390. key += ':' + indexData.id;
  41391. }
  41392. for ( let i = 0; i < attributes.length; i ++ ) {
  41393. const attributeData = this.get( attributes[ i ] );
  41394. key += ':' + attributeData.id;
  41395. }
  41396. return key;
  41397. }
  41398. /**
  41399. * Creates a VAO from the index and attributes.
  41400. *
  41401. * @private
  41402. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41403. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41404. * @return {Object} The VAO data.
  41405. */
  41406. _createVao( index, attributes ) {
  41407. const { gl } = this;
  41408. const vaoGPU = gl.createVertexArray();
  41409. let key = '';
  41410. let staticVao = true;
  41411. gl.bindVertexArray( vaoGPU );
  41412. if ( index !== null ) {
  41413. const indexData = this.get( index );
  41414. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41415. key += ':' + indexData.id;
  41416. }
  41417. for ( let i = 0; i < attributes.length; i ++ ) {
  41418. const attribute = attributes[ i ];
  41419. const attributeData = this.get( attribute );
  41420. key += ':' + attributeData.id;
  41421. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41422. gl.enableVertexAttribArray( i );
  41423. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41424. let stride, offset;
  41425. if ( attribute.isInterleavedBufferAttribute === true ) {
  41426. stride = attribute.data.stride * attributeData.bytesPerElement;
  41427. offset = attribute.offset * attributeData.bytesPerElement;
  41428. } else {
  41429. stride = 0;
  41430. offset = 0;
  41431. }
  41432. if ( attributeData.isInteger ) {
  41433. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41434. } else {
  41435. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41436. }
  41437. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41438. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41439. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41440. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41441. }
  41442. }
  41443. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41444. this.vaoCache[ key ] = vaoGPU;
  41445. return { vaoGPU, staticVao };
  41446. }
  41447. /**
  41448. * Creates a transform feedback from the given transform buffers.
  41449. *
  41450. * @private
  41451. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  41452. * @return {WebGLTransformFeedback} The transform feedback.
  41453. */
  41454. _getTransformFeedback( transformBuffers ) {
  41455. let key = '';
  41456. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41457. key += ':' + transformBuffers[ i ].id;
  41458. }
  41459. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41460. if ( transformFeedbackGPU !== undefined ) {
  41461. return transformFeedbackGPU;
  41462. }
  41463. const { gl } = this;
  41464. transformFeedbackGPU = gl.createTransformFeedback();
  41465. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41466. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41467. const attributeData = transformBuffers[ i ];
  41468. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41469. }
  41470. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41471. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41472. return transformFeedbackGPU;
  41473. }
  41474. /**
  41475. * Setups the given bindings.
  41476. *
  41477. * @private
  41478. * @param {Array<BindGroup>} bindings - The bindings.
  41479. * @param {WebGLProgram} programGPU - The WebGL program.
  41480. */
  41481. _setupBindings( bindings, programGPU ) {
  41482. const gl = this.gl;
  41483. for ( const bindGroup of bindings ) {
  41484. for ( const binding of bindGroup.bindings ) {
  41485. const bindingData = this.get( binding );
  41486. const index = bindingData.index;
  41487. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41488. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41489. gl.uniformBlockBinding( programGPU, location, index );
  41490. } else if ( binding.isSampledTexture ) {
  41491. const location = gl.getUniformLocation( programGPU, binding.name );
  41492. gl.uniform1i( location, index );
  41493. }
  41494. }
  41495. }
  41496. }
  41497. /**
  41498. * Binds the given uniforms.
  41499. *
  41500. * @private
  41501. * @param {Array<BindGroup>} bindings - The bindings.
  41502. */
  41503. _bindUniforms( bindings ) {
  41504. const { gl, state } = this;
  41505. for ( const bindGroup of bindings ) {
  41506. for ( const binding of bindGroup.bindings ) {
  41507. const bindingData = this.get( binding );
  41508. const index = bindingData.index;
  41509. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41510. // TODO USE bindBufferRange to group multiple uniform buffers
  41511. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41512. } else if ( binding.isSampledTexture ) {
  41513. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41514. }
  41515. }
  41516. }
  41517. }
  41518. /**
  41519. * Frees internal resources.
  41520. */
  41521. dispose() {
  41522. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41523. }
  41524. }
  41525. const GPUPrimitiveTopology = {
  41526. PointList: 'point-list',
  41527. LineList: 'line-list',
  41528. LineStrip: 'line-strip',
  41529. TriangleList: 'triangle-list',
  41530. TriangleStrip: 'triangle-strip',
  41531. };
  41532. const GPUCompareFunction = {
  41533. Never: 'never',
  41534. Less: 'less',
  41535. Equal: 'equal',
  41536. LessEqual: 'less-equal',
  41537. Greater: 'greater',
  41538. NotEqual: 'not-equal',
  41539. GreaterEqual: 'greater-equal',
  41540. Always: 'always'
  41541. };
  41542. const GPUStoreOp = {
  41543. Store: 'store',
  41544. Discard: 'discard'
  41545. };
  41546. const GPULoadOp = {
  41547. Load: 'load',
  41548. Clear: 'clear'
  41549. };
  41550. const GPUFrontFace = {
  41551. CCW: 'ccw',
  41552. CW: 'cw'
  41553. };
  41554. const GPUCullMode = {
  41555. None: 'none',
  41556. Front: 'front',
  41557. Back: 'back'
  41558. };
  41559. const GPUIndexFormat = {
  41560. Uint16: 'uint16',
  41561. Uint32: 'uint32'
  41562. };
  41563. const GPUTextureFormat = {
  41564. // 8-bit formats
  41565. R8Unorm: 'r8unorm',
  41566. R8Snorm: 'r8snorm',
  41567. R8Uint: 'r8uint',
  41568. R8Sint: 'r8sint',
  41569. // 16-bit formats
  41570. R16Uint: 'r16uint',
  41571. R16Sint: 'r16sint',
  41572. R16Float: 'r16float',
  41573. RG8Unorm: 'rg8unorm',
  41574. RG8Snorm: 'rg8snorm',
  41575. RG8Uint: 'rg8uint',
  41576. RG8Sint: 'rg8sint',
  41577. // 32-bit formats
  41578. R32Uint: 'r32uint',
  41579. R32Sint: 'r32sint',
  41580. R32Float: 'r32float',
  41581. RG16Uint: 'rg16uint',
  41582. RG16Sint: 'rg16sint',
  41583. RG16Float: 'rg16float',
  41584. RGBA8Unorm: 'rgba8unorm',
  41585. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  41586. RGBA8Snorm: 'rgba8snorm',
  41587. RGBA8Uint: 'rgba8uint',
  41588. RGBA8Sint: 'rgba8sint',
  41589. BGRA8Unorm: 'bgra8unorm',
  41590. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  41591. // Packed 32-bit formats
  41592. RGB9E5UFloat: 'rgb9e5ufloat',
  41593. RGB10A2Unorm: 'rgb10a2unorm',
  41594. RG11B10uFloat: 'rgb10a2unorm',
  41595. // 64-bit formats
  41596. RG32Uint: 'rg32uint',
  41597. RG32Sint: 'rg32sint',
  41598. RG32Float: 'rg32float',
  41599. RGBA16Uint: 'rgba16uint',
  41600. RGBA16Sint: 'rgba16sint',
  41601. RGBA16Float: 'rgba16float',
  41602. // 128-bit formats
  41603. RGBA32Uint: 'rgba32uint',
  41604. RGBA32Sint: 'rgba32sint',
  41605. RGBA32Float: 'rgba32float',
  41606. // Depth and stencil formats
  41607. Stencil8: 'stencil8',
  41608. Depth16Unorm: 'depth16unorm',
  41609. Depth24Plus: 'depth24plus',
  41610. Depth24PlusStencil8: 'depth24plus-stencil8',
  41611. Depth32Float: 'depth32float',
  41612. // 'depth32float-stencil8' extension
  41613. Depth32FloatStencil8: 'depth32float-stencil8',
  41614. // BC compressed formats usable if 'texture-compression-bc' is both
  41615. // supported by the device/user agent and enabled in requestDevice.
  41616. BC1RGBAUnorm: 'bc1-rgba-unorm',
  41617. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  41618. BC2RGBAUnorm: 'bc2-rgba-unorm',
  41619. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  41620. BC3RGBAUnorm: 'bc3-rgba-unorm',
  41621. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  41622. BC4RUnorm: 'bc4-r-unorm',
  41623. BC4RSnorm: 'bc4-r-snorm',
  41624. BC5RGUnorm: 'bc5-rg-unorm',
  41625. BC5RGSnorm: 'bc5-rg-snorm',
  41626. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  41627. BC6HRGBFloat: 'bc6h-rgb-float',
  41628. BC7RGBAUnorm: 'bc7-rgba-unorm',
  41629. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  41630. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  41631. // supported by the device/user agent and enabled in requestDevice.
  41632. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  41633. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  41634. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  41635. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  41636. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  41637. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  41638. EACR11Unorm: 'eac-r11unorm',
  41639. EACR11Snorm: 'eac-r11snorm',
  41640. EACRG11Unorm: 'eac-rg11unorm',
  41641. EACRG11Snorm: 'eac-rg11snorm',
  41642. // ASTC compressed formats usable if 'texture-compression-astc' is both
  41643. // supported by the device/user agent and enabled in requestDevice.
  41644. ASTC4x4Unorm: 'astc-4x4-unorm',
  41645. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  41646. ASTC5x4Unorm: 'astc-5x4-unorm',
  41647. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  41648. ASTC5x5Unorm: 'astc-5x5-unorm',
  41649. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  41650. ASTC6x5Unorm: 'astc-6x5-unorm',
  41651. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  41652. ASTC6x6Unorm: 'astc-6x6-unorm',
  41653. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  41654. ASTC8x5Unorm: 'astc-8x5-unorm',
  41655. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  41656. ASTC8x6Unorm: 'astc-8x6-unorm',
  41657. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  41658. ASTC8x8Unorm: 'astc-8x8-unorm',
  41659. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  41660. ASTC10x5Unorm: 'astc-10x5-unorm',
  41661. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  41662. ASTC10x6Unorm: 'astc-10x6-unorm',
  41663. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  41664. ASTC10x8Unorm: 'astc-10x8-unorm',
  41665. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  41666. ASTC10x10Unorm: 'astc-10x10-unorm',
  41667. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  41668. ASTC12x10Unorm: 'astc-12x10-unorm',
  41669. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  41670. ASTC12x12Unorm: 'astc-12x12-unorm',
  41671. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  41672. };
  41673. const GPUAddressMode = {
  41674. ClampToEdge: 'clamp-to-edge',
  41675. Repeat: 'repeat',
  41676. MirrorRepeat: 'mirror-repeat'
  41677. };
  41678. const GPUFilterMode = {
  41679. Linear: 'linear',
  41680. Nearest: 'nearest'
  41681. };
  41682. const GPUBlendFactor = {
  41683. Zero: 'zero',
  41684. One: 'one',
  41685. Src: 'src',
  41686. OneMinusSrc: 'one-minus-src',
  41687. SrcAlpha: 'src-alpha',
  41688. OneMinusSrcAlpha: 'one-minus-src-alpha',
  41689. Dst: 'dst',
  41690. OneMinusDstColor: 'one-minus-dst',
  41691. DstAlpha: 'dst-alpha',
  41692. OneMinusDstAlpha: 'one-minus-dst-alpha',
  41693. SrcAlphaSaturated: 'src-alpha-saturated',
  41694. Constant: 'constant',
  41695. OneMinusConstant: 'one-minus-constant'
  41696. };
  41697. const GPUBlendOperation = {
  41698. Add: 'add',
  41699. Subtract: 'subtract',
  41700. ReverseSubtract: 'reverse-subtract',
  41701. Min: 'min',
  41702. Max: 'max'
  41703. };
  41704. const GPUColorWriteFlags = {
  41705. None: 0,
  41706. Red: 0x1,
  41707. Green: 0x2,
  41708. Blue: 0x4,
  41709. Alpha: 0x8,
  41710. All: 0xF
  41711. };
  41712. const GPUStencilOperation = {
  41713. Keep: 'keep',
  41714. Zero: 'zero',
  41715. Replace: 'replace',
  41716. Invert: 'invert',
  41717. IncrementClamp: 'increment-clamp',
  41718. DecrementClamp: 'decrement-clamp',
  41719. IncrementWrap: 'increment-wrap',
  41720. DecrementWrap: 'decrement-wrap'
  41721. };
  41722. const GPUBufferBindingType = {
  41723. Uniform: 'uniform',
  41724. Storage: 'storage',
  41725. ReadOnlyStorage: 'read-only-storage'
  41726. };
  41727. const GPUStorageTextureAccess = {
  41728. WriteOnly: 'write-only',
  41729. ReadOnly: 'read-only',
  41730. ReadWrite: 'read-write',
  41731. };
  41732. const GPUTextureSampleType = {
  41733. Float: 'float',
  41734. UnfilterableFloat: 'unfilterable-float',
  41735. Depth: 'depth',
  41736. SInt: 'sint',
  41737. UInt: 'uint'
  41738. };
  41739. const GPUTextureDimension = {
  41740. OneD: '1d',
  41741. TwoD: '2d',
  41742. ThreeD: '3d'
  41743. };
  41744. const GPUTextureViewDimension = {
  41745. OneD: '1d',
  41746. TwoD: '2d',
  41747. TwoDArray: '2d-array',
  41748. Cube: 'cube',
  41749. CubeArray: 'cube-array',
  41750. ThreeD: '3d'
  41751. };
  41752. const GPUTextureAspect = {
  41753. All: 'all',
  41754. StencilOnly: 'stencil-only',
  41755. DepthOnly: 'depth-only'
  41756. };
  41757. const GPUInputStepMode = {
  41758. Vertex: 'vertex',
  41759. Instance: 'instance'
  41760. };
  41761. const GPUFeatureName = {
  41762. DepthClipControl: 'depth-clip-control',
  41763. Depth32FloatStencil8: 'depth32float-stencil8',
  41764. TextureCompressionBC: 'texture-compression-bc',
  41765. TextureCompressionETC2: 'texture-compression-etc2',
  41766. TextureCompressionASTC: 'texture-compression-astc',
  41767. TimestampQuery: 'timestamp-query',
  41768. IndirectFirstInstance: 'indirect-first-instance',
  41769. ShaderF16: 'shader-f16',
  41770. RG11B10UFloat: 'rg11b10ufloat-renderable',
  41771. BGRA8UNormStorage: 'bgra8unorm-storage',
  41772. Float32Filterable: 'float32-filterable',
  41773. ClipDistances: 'clip-distances',
  41774. DualSourceBlending: 'dual-source-blending',
  41775. Subgroups: 'subgroups'
  41776. };
  41777. /**
  41778. * Represents a sampler binding type.
  41779. *
  41780. * @private
  41781. * @augments Binding
  41782. */
  41783. class Sampler extends Binding {
  41784. /**
  41785. * Constructs a new sampler.
  41786. *
  41787. * @param {String} name - The samplers's name.
  41788. * @param {Texture?} texture - The texture this binding is referring to.
  41789. */
  41790. constructor( name, texture ) {
  41791. super( name );
  41792. /**
  41793. * The texture the sampler is referring to.
  41794. *
  41795. * @type {Texture?}
  41796. */
  41797. this.texture = texture;
  41798. /**
  41799. * The binding's version.
  41800. *
  41801. * @type {Number}
  41802. */
  41803. this.version = texture ? texture.version : 0;
  41804. /**
  41805. * This flag can be used for type testing.
  41806. *
  41807. * @type {Boolean}
  41808. * @readonly
  41809. * @default true
  41810. */
  41811. this.isSampler = true;
  41812. }
  41813. }
  41814. /**
  41815. * A special form of sampler binding type.
  41816. * It's texture value is managed by a node object.
  41817. *
  41818. * @private
  41819. * @augments Sampler
  41820. */
  41821. class NodeSampler extends Sampler {
  41822. /**
  41823. * Constructs a new node-based sampler.
  41824. *
  41825. * @param {String} name - The samplers's name.
  41826. * @param {TextureNode} textureNode - The texture node.
  41827. * @param {UniformGroupNode} groupNode - The uniform group node.
  41828. */
  41829. constructor( name, textureNode, groupNode ) {
  41830. super( name, textureNode ? textureNode.value : null );
  41831. /**
  41832. * The texture node.
  41833. *
  41834. * @type {TextureNode}
  41835. */
  41836. this.textureNode = textureNode;
  41837. /**
  41838. * The uniform group node.
  41839. *
  41840. * @type {UniformGroupNode}
  41841. */
  41842. this.groupNode = groupNode;
  41843. }
  41844. /**
  41845. * Updates the texture value of this sampler.
  41846. */
  41847. update() {
  41848. this.texture = this.textureNode.value;
  41849. }
  41850. }
  41851. /**
  41852. * Represents a storage buffer binding type.
  41853. *
  41854. * @private
  41855. * @augments Buffer
  41856. */
  41857. class StorageBuffer extends Buffer {
  41858. /**
  41859. * Constructs a new uniform buffer.
  41860. *
  41861. * @param {String} name - The buffer's name.
  41862. * @param {BufferAttribute} attribute - The buffer attribute.
  41863. */
  41864. constructor( name, attribute ) {
  41865. super( name, attribute ? attribute.array : null );
  41866. /**
  41867. * This flag can be used for type testing.
  41868. *
  41869. * @type {BufferAttribute}
  41870. */
  41871. this.attribute = attribute;
  41872. /**
  41873. * This flag can be used for type testing.
  41874. *
  41875. * @type {Boolean}
  41876. * @readonly
  41877. * @default true
  41878. */
  41879. this.isStorageBuffer = true;
  41880. }
  41881. }
  41882. let _id = 0;
  41883. /**
  41884. * A special form of storage buffer binding type.
  41885. * It's buffer value is managed by a node object.
  41886. *
  41887. * @private
  41888. * @augments StorageBuffer
  41889. */
  41890. class NodeStorageBuffer extends StorageBuffer {
  41891. /**
  41892. * Constructs a new node-based storage buffer.
  41893. *
  41894. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  41895. * @param {UniformGroupNode} groupNode - The uniform group node.
  41896. */
  41897. constructor( nodeUniform, groupNode ) {
  41898. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41899. /**
  41900. * The node uniform.
  41901. *
  41902. * @type {StorageBufferNode}
  41903. */
  41904. this.nodeUniform = nodeUniform;
  41905. /**
  41906. * The access type.
  41907. *
  41908. * @type {String}
  41909. */
  41910. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  41911. /**
  41912. * The uniform group node.
  41913. *
  41914. * @type {UniformGroupNode}
  41915. */
  41916. this.groupNode = groupNode;
  41917. }
  41918. /**
  41919. * The storage buffer.
  41920. *
  41921. * @type {BufferAttribute}
  41922. */
  41923. get buffer() {
  41924. return this.nodeUniform.value;
  41925. }
  41926. }
  41927. /**
  41928. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  41929. *
  41930. * @private
  41931. */
  41932. class WebGPUTexturePassUtils extends DataMap {
  41933. /**
  41934. * Constructs a new utility object.
  41935. *
  41936. * @param {GPUDevice} device - The WebGPU device.
  41937. */
  41938. constructor( device ) {
  41939. super();
  41940. /**
  41941. * The WebGPU device.
  41942. *
  41943. * @type {GPUDevice}
  41944. */
  41945. this.device = device;
  41946. const mipmapVertexSource = `
  41947. struct VarysStruct {
  41948. @builtin( position ) Position: vec4<f32>,
  41949. @location( 0 ) vTex : vec2<f32>
  41950. };
  41951. @vertex
  41952. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41953. var Varys : VarysStruct;
  41954. var pos = array< vec2<f32>, 4 >(
  41955. vec2<f32>( -1.0, 1.0 ),
  41956. vec2<f32>( 1.0, 1.0 ),
  41957. vec2<f32>( -1.0, -1.0 ),
  41958. vec2<f32>( 1.0, -1.0 )
  41959. );
  41960. var tex = array< vec2<f32>, 4 >(
  41961. vec2<f32>( 0.0, 0.0 ),
  41962. vec2<f32>( 1.0, 0.0 ),
  41963. vec2<f32>( 0.0, 1.0 ),
  41964. vec2<f32>( 1.0, 1.0 )
  41965. );
  41966. Varys.vTex = tex[ vertexIndex ];
  41967. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41968. return Varys;
  41969. }
  41970. `;
  41971. const mipmapFragmentSource = `
  41972. @group( 0 ) @binding( 0 )
  41973. var imgSampler : sampler;
  41974. @group( 0 ) @binding( 1 )
  41975. var img : texture_2d<f32>;
  41976. @fragment
  41977. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41978. return textureSample( img, imgSampler, vTex );
  41979. }
  41980. `;
  41981. const flipYFragmentSource = `
  41982. @group( 0 ) @binding( 0 )
  41983. var imgSampler : sampler;
  41984. @group( 0 ) @binding( 1 )
  41985. var img : texture_2d<f32>;
  41986. @fragment
  41987. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41988. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41989. }
  41990. `;
  41991. /**
  41992. * The mipmap GPU sampler.
  41993. *
  41994. * @type {GPUSampler}
  41995. */
  41996. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41997. /**
  41998. * The flipY GPU sampler.
  41999. *
  42000. * @type {GPUSampler}
  42001. */
  42002. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42003. /**
  42004. * A cache for GPU render pipelines used for copy/transfer passes.
  42005. * Every texture format requires a unique pipeline.
  42006. *
  42007. * @type {Object<String,GPURenderPipeline>}
  42008. */
  42009. this.transferPipelines = {};
  42010. /**
  42011. * A cache for GPU render pipelines used for flipY passes.
  42012. * Every texture format requires a unique pipeline.
  42013. *
  42014. * @type {Object<String,GPURenderPipeline>}
  42015. */
  42016. this.flipYPipelines = {};
  42017. /**
  42018. * The mipmap vertex shader module.
  42019. *
  42020. * @type {GPUShaderModule}
  42021. */
  42022. this.mipmapVertexShaderModule = device.createShaderModule( {
  42023. label: 'mipmapVertex',
  42024. code: mipmapVertexSource
  42025. } );
  42026. /**
  42027. * The mipmap fragment shader module.
  42028. *
  42029. * @type {GPUShaderModule}
  42030. */
  42031. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42032. label: 'mipmapFragment',
  42033. code: mipmapFragmentSource
  42034. } );
  42035. /**
  42036. * The flipY fragment shader module.
  42037. *
  42038. * @type {GPUShaderModule}
  42039. */
  42040. this.flipYFragmentShaderModule = device.createShaderModule( {
  42041. label: 'flipYFragment',
  42042. code: flipYFragmentSource
  42043. } );
  42044. }
  42045. /**
  42046. * Returns a render pipeline for the internal copy render pass. The pass
  42047. * requires a unique render pipeline for each texture format.
  42048. *
  42049. * @param {String} format - The GPU texture format
  42050. * @return {GPURenderPipeline} The GPU render pipeline.
  42051. */
  42052. getTransferPipeline( format ) {
  42053. let pipeline = this.transferPipelines[ format ];
  42054. if ( pipeline === undefined ) {
  42055. pipeline = this.device.createRenderPipeline( {
  42056. label: `mipmap-${ format }`,
  42057. vertex: {
  42058. module: this.mipmapVertexShaderModule,
  42059. entryPoint: 'main'
  42060. },
  42061. fragment: {
  42062. module: this.mipmapFragmentShaderModule,
  42063. entryPoint: 'main',
  42064. targets: [ { format } ]
  42065. },
  42066. primitive: {
  42067. topology: GPUPrimitiveTopology.TriangleStrip,
  42068. stripIndexFormat: GPUIndexFormat.Uint32
  42069. },
  42070. layout: 'auto'
  42071. } );
  42072. this.transferPipelines[ format ] = pipeline;
  42073. }
  42074. return pipeline;
  42075. }
  42076. /**
  42077. * Returns a render pipeline for the flipY render pass. The pass
  42078. * requires a unique render pipeline for each texture format.
  42079. *
  42080. * @param {String} format - The GPU texture format
  42081. * @return {GPURenderPipeline} The GPU render pipeline.
  42082. */
  42083. getFlipYPipeline( format ) {
  42084. let pipeline = this.flipYPipelines[ format ];
  42085. if ( pipeline === undefined ) {
  42086. pipeline = this.device.createRenderPipeline( {
  42087. label: `flipY-${ format }`,
  42088. vertex: {
  42089. module: this.mipmapVertexShaderModule,
  42090. entryPoint: 'main'
  42091. },
  42092. fragment: {
  42093. module: this.flipYFragmentShaderModule,
  42094. entryPoint: 'main',
  42095. targets: [ { format } ]
  42096. },
  42097. primitive: {
  42098. topology: GPUPrimitiveTopology.TriangleStrip,
  42099. stripIndexFormat: GPUIndexFormat.Uint32
  42100. },
  42101. layout: 'auto'
  42102. } );
  42103. this.flipYPipelines[ format ] = pipeline;
  42104. }
  42105. return pipeline;
  42106. }
  42107. /**
  42108. * Flip the contents of the given GPU texture along its vertical axis.
  42109. *
  42110. * @param {GPUTexture} textureGPU - The GPU texture object.
  42111. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42112. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42113. */
  42114. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42115. const format = textureGPUDescriptor.format;
  42116. const { width, height } = textureGPUDescriptor.size;
  42117. const transferPipeline = this.getTransferPipeline( format );
  42118. const flipYPipeline = this.getFlipYPipeline( format );
  42119. const tempTexture = this.device.createTexture( {
  42120. size: { width, height, depthOrArrayLayers: 1 },
  42121. format,
  42122. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42123. } );
  42124. const srcView = textureGPU.createView( {
  42125. baseMipLevel: 0,
  42126. mipLevelCount: 1,
  42127. dimension: GPUTextureViewDimension.TwoD,
  42128. baseArrayLayer
  42129. } );
  42130. const dstView = tempTexture.createView( {
  42131. baseMipLevel: 0,
  42132. mipLevelCount: 1,
  42133. dimension: GPUTextureViewDimension.TwoD,
  42134. baseArrayLayer: 0
  42135. } );
  42136. const commandEncoder = this.device.createCommandEncoder( {} );
  42137. const pass = ( pipeline, sourceView, destinationView ) => {
  42138. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42139. const bindGroup = this.device.createBindGroup( {
  42140. layout: bindGroupLayout,
  42141. entries: [ {
  42142. binding: 0,
  42143. resource: this.flipYSampler
  42144. }, {
  42145. binding: 1,
  42146. resource: sourceView
  42147. } ]
  42148. } );
  42149. const passEncoder = commandEncoder.beginRenderPass( {
  42150. colorAttachments: [ {
  42151. view: destinationView,
  42152. loadOp: GPULoadOp.Clear,
  42153. storeOp: GPUStoreOp.Store,
  42154. clearValue: [ 0, 0, 0, 0 ]
  42155. } ]
  42156. } );
  42157. passEncoder.setPipeline( pipeline );
  42158. passEncoder.setBindGroup( 0, bindGroup );
  42159. passEncoder.draw( 4, 1, 0, 0 );
  42160. passEncoder.end();
  42161. };
  42162. pass( transferPipeline, srcView, dstView );
  42163. pass( flipYPipeline, dstView, srcView );
  42164. this.device.queue.submit( [ commandEncoder.finish() ] );
  42165. tempTexture.destroy();
  42166. }
  42167. /**
  42168. * Generates mipmaps for the given GPU texture.
  42169. *
  42170. * @param {GPUTexture} textureGPU - The GPU texture object.
  42171. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42172. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42173. */
  42174. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42175. const textureData = this.get( textureGPU );
  42176. if ( textureData.useCount === undefined ) {
  42177. textureData.useCount = 0;
  42178. textureData.layers = [];
  42179. }
  42180. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42181. const commandEncoder = this.device.createCommandEncoder( {} );
  42182. this._mipmapRunBundles( commandEncoder, passes );
  42183. this.device.queue.submit( [ commandEncoder.finish() ] );
  42184. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42185. textureData.useCount ++;
  42186. }
  42187. /**
  42188. * Since multiple copy render passes are required to generate mipmaps, the passes
  42189. * are managed as render bundles to improve performance.
  42190. *
  42191. * @param {GPUTexture} textureGPU - The GPU texture object.
  42192. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42193. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  42194. * @return {Array} An array of render bundles.
  42195. */
  42196. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42197. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42198. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42199. let srcView = textureGPU.createView( {
  42200. baseMipLevel: 0,
  42201. mipLevelCount: 1,
  42202. dimension: GPUTextureViewDimension.TwoD,
  42203. baseArrayLayer
  42204. } );
  42205. const passes = [];
  42206. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42207. const bindGroup = this.device.createBindGroup( {
  42208. layout: bindGroupLayout,
  42209. entries: [ {
  42210. binding: 0,
  42211. resource: this.mipmapSampler
  42212. }, {
  42213. binding: 1,
  42214. resource: srcView
  42215. } ]
  42216. } );
  42217. const dstView = textureGPU.createView( {
  42218. baseMipLevel: i,
  42219. mipLevelCount: 1,
  42220. dimension: GPUTextureViewDimension.TwoD,
  42221. baseArrayLayer
  42222. } );
  42223. const passDescriptor = {
  42224. colorAttachments: [ {
  42225. view: dstView,
  42226. loadOp: GPULoadOp.Clear,
  42227. storeOp: GPUStoreOp.Store,
  42228. clearValue: [ 0, 0, 0, 0 ]
  42229. } ]
  42230. };
  42231. const passEncoder = this.device.createRenderBundleEncoder( {
  42232. colorFormats: [ textureGPUDescriptor.format ]
  42233. } );
  42234. passEncoder.setPipeline( pipeline );
  42235. passEncoder.setBindGroup( 0, bindGroup );
  42236. passEncoder.draw( 4, 1, 0, 0 );
  42237. passes.push( {
  42238. renderBundles: [ passEncoder.finish() ],
  42239. passDescriptor
  42240. } );
  42241. srcView = dstView;
  42242. }
  42243. return passes;
  42244. }
  42245. /**
  42246. * Executes the render bundles.
  42247. *
  42248. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  42249. * @param {Array} passes - An array of render bundles.
  42250. */
  42251. _mipmapRunBundles( commandEncoder, passes ) {
  42252. const levels = passes.length;
  42253. for ( let i = 0; i < levels; i ++ ) {
  42254. const pass = passes[ i ];
  42255. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42256. passEncoder.executeBundles( pass.renderBundles );
  42257. passEncoder.end();
  42258. }
  42259. }
  42260. }
  42261. const _compareToWebGPU = {
  42262. [ NeverCompare ]: 'never',
  42263. [ LessCompare ]: 'less',
  42264. [ EqualCompare ]: 'equal',
  42265. [ LessEqualCompare ]: 'less-equal',
  42266. [ GreaterCompare ]: 'greater',
  42267. [ GreaterEqualCompare ]: 'greater-equal',
  42268. [ AlwaysCompare ]: 'always',
  42269. [ NotEqualCompare ]: 'not-equal'
  42270. };
  42271. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42272. /**
  42273. * A WebGPU backend utility module for managing textures.
  42274. *
  42275. * @private
  42276. */
  42277. class WebGPUTextureUtils {
  42278. /**
  42279. * Constructs a new utility object.
  42280. *
  42281. * @param {WebGPUBackend} backend - The WebGPU backend.
  42282. */
  42283. constructor( backend ) {
  42284. /**
  42285. * A reference to the WebGPU backend.
  42286. *
  42287. * @type {WebGPUBackend}
  42288. */
  42289. this.backend = backend;
  42290. /**
  42291. * A reference to the pass utils.
  42292. *
  42293. * @type {WebGPUTexturePassUtils?}
  42294. * @default null
  42295. */
  42296. this._passUtils = null;
  42297. /**
  42298. * A dictionary for managing default textures. The key
  42299. * is the texture format, the value the texture object.
  42300. *
  42301. * @type {Object<String,Texture>}
  42302. */
  42303. this.defaultTexture = {};
  42304. /**
  42305. * A dictionary for managing default cube textures. The key
  42306. * is the texture format, the value the texture object.
  42307. *
  42308. * @type {Object<String,CubeTexture>}
  42309. */
  42310. this.defaultCubeTexture = {};
  42311. /**
  42312. * A default video frame.
  42313. *
  42314. * @type {VideoFrame?}
  42315. * @default null
  42316. */
  42317. this.defaultVideoFrame = null;
  42318. /**
  42319. * Represents the color attachment of the default framebuffer.
  42320. *
  42321. * @type {GPUTexture?}
  42322. * @default null
  42323. */
  42324. this.colorBuffer = null;
  42325. /**
  42326. * Represents the depth attachment of the default framebuffer.
  42327. *
  42328. * @type {DepthTexture}
  42329. */
  42330. this.depthTexture = new DepthTexture();
  42331. this.depthTexture.name = 'depthBuffer';
  42332. }
  42333. /**
  42334. * Creates a GPU sampler for the given texture.
  42335. *
  42336. * @param {Texture} texture - The texture to create the sampler for.
  42337. */
  42338. createSampler( texture ) {
  42339. const backend = this.backend;
  42340. const device = backend.device;
  42341. const textureGPU = backend.get( texture );
  42342. const samplerDescriptorGPU = {
  42343. addressModeU: this._convertAddressMode( texture.wrapS ),
  42344. addressModeV: this._convertAddressMode( texture.wrapT ),
  42345. addressModeW: this._convertAddressMode( texture.wrapR ),
  42346. magFilter: this._convertFilterMode( texture.magFilter ),
  42347. minFilter: this._convertFilterMode( texture.minFilter ),
  42348. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42349. maxAnisotropy: 1
  42350. };
  42351. // anisotropy can only be used when all filter modes are set to linear.
  42352. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42353. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42354. }
  42355. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42356. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42357. }
  42358. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42359. }
  42360. /**
  42361. * Creates a default texture for the given texture that can be used
  42362. * as a placeholder until the actual texture is ready for usage.
  42363. *
  42364. * @param {Texture} texture - The texture to create a default texture for.
  42365. */
  42366. createDefaultTexture( texture ) {
  42367. let textureGPU;
  42368. const format = getFormat( texture );
  42369. if ( texture.isCubeTexture ) {
  42370. textureGPU = this._getDefaultCubeTextureGPU( format );
  42371. } else if ( texture.isVideoTexture ) {
  42372. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42373. } else {
  42374. textureGPU = this._getDefaultTextureGPU( format );
  42375. }
  42376. this.backend.get( texture ).texture = textureGPU;
  42377. }
  42378. /**
  42379. * Defines a texture on the GPU for the given texture object.
  42380. *
  42381. * @param {Texture} texture - The texture.
  42382. * @param {Object} [options={}] - Optional configuration parameter.
  42383. * @return {undefined}
  42384. */
  42385. createTexture( texture, options = {} ) {
  42386. const backend = this.backend;
  42387. const textureData = backend.get( texture );
  42388. if ( textureData.initialized ) {
  42389. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42390. }
  42391. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42392. if ( options.levels === undefined ) options.levels = 1;
  42393. if ( options.depth === undefined ) options.depth = 1;
  42394. const { width, height, depth, levels } = options;
  42395. if ( texture.isFramebufferTexture ) {
  42396. if ( options.renderTarget ) {
  42397. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42398. } else {
  42399. options.format = this.backend.utils.getPreferredCanvasFormat();
  42400. }
  42401. }
  42402. const dimension = this._getDimension( texture );
  42403. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42404. textureData.format = format;
  42405. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  42406. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42407. if ( texture.isStorageTexture === true ) {
  42408. usage |= GPUTextureUsage.STORAGE_BINDING;
  42409. }
  42410. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42411. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42412. }
  42413. const textureDescriptorGPU = {
  42414. label: texture.name,
  42415. size: {
  42416. width: width,
  42417. height: height,
  42418. depthOrArrayLayers: depth,
  42419. },
  42420. mipLevelCount: levels,
  42421. sampleCount: primarySamples,
  42422. dimension: dimension,
  42423. format: format,
  42424. usage: usage
  42425. };
  42426. // texture creation
  42427. if ( texture.isVideoTexture ) {
  42428. const video = texture.source.data;
  42429. const videoFrame = new VideoFrame( video );
  42430. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42431. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42432. videoFrame.close();
  42433. textureData.externalTexture = video;
  42434. } else {
  42435. if ( format === undefined ) {
  42436. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42437. return this.createDefaultTexture( texture );
  42438. }
  42439. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42440. }
  42441. if ( isMSAA ) {
  42442. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42443. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42444. msaaTextureDescriptorGPU.sampleCount = samples;
  42445. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42446. }
  42447. textureData.initialized = true;
  42448. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42449. }
  42450. /**
  42451. * Destroys the GPU data for the given texture object.
  42452. *
  42453. * @param {Texture} texture - The texture.
  42454. */
  42455. destroyTexture( texture ) {
  42456. const backend = this.backend;
  42457. const textureData = backend.get( texture );
  42458. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  42459. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42460. backend.delete( texture );
  42461. }
  42462. /**
  42463. * Destroys the GPU sampler for the given texture.
  42464. *
  42465. * @param {Texture} texture - The texture to destroy the sampler for.
  42466. */
  42467. destroySampler( texture ) {
  42468. const backend = this.backend;
  42469. const textureData = backend.get( texture );
  42470. delete textureData.sampler;
  42471. }
  42472. /**
  42473. * Generates mipmaps for the given texture.
  42474. *
  42475. * @param {Texture} texture - The texture.
  42476. */
  42477. generateMipmaps( texture ) {
  42478. const textureData = this.backend.get( texture );
  42479. if ( texture.isCubeTexture ) {
  42480. for ( let i = 0; i < 6; i ++ ) {
  42481. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42482. }
  42483. } else {
  42484. const depth = texture.image.depth || 1;
  42485. for ( let i = 0; i < depth; i ++ ) {
  42486. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42487. }
  42488. }
  42489. }
  42490. /**
  42491. * Returns the color buffer representing the color
  42492. * attachment of the default framebuffer.
  42493. *
  42494. * @return {GPUTexture} The color buffer.
  42495. */
  42496. getColorBuffer() {
  42497. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42498. const backend = this.backend;
  42499. const { width, height } = backend.getDrawingBufferSize();
  42500. this.colorBuffer = backend.device.createTexture( {
  42501. label: 'colorBuffer',
  42502. size: {
  42503. width: width,
  42504. height: height,
  42505. depthOrArrayLayers: 1
  42506. },
  42507. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42508. format: backend.utils.getPreferredCanvasFormat(),
  42509. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42510. } );
  42511. return this.colorBuffer;
  42512. }
  42513. /**
  42514. * Returns the depth buffer representing the depth
  42515. * attachment of the default framebuffer.
  42516. *
  42517. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  42518. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  42519. * @return {GPUTexture} The depth buffer.
  42520. */
  42521. getDepthBuffer( depth = true, stencil = false ) {
  42522. const backend = this.backend;
  42523. const { width, height } = backend.getDrawingBufferSize();
  42524. const depthTexture = this.depthTexture;
  42525. const depthTextureGPU = backend.get( depthTexture ).texture;
  42526. let format, type;
  42527. if ( stencil ) {
  42528. format = DepthStencilFormat;
  42529. type = UnsignedInt248Type;
  42530. } else if ( depth ) {
  42531. format = DepthFormat;
  42532. type = UnsignedIntType;
  42533. }
  42534. if ( depthTextureGPU !== undefined ) {
  42535. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42536. return depthTextureGPU;
  42537. }
  42538. this.destroyTexture( depthTexture );
  42539. }
  42540. depthTexture.name = 'depthBuffer';
  42541. depthTexture.format = format;
  42542. depthTexture.type = type;
  42543. depthTexture.image.width = width;
  42544. depthTexture.image.height = height;
  42545. this.createTexture( depthTexture, { width, height } );
  42546. return backend.get( depthTexture ).texture;
  42547. }
  42548. /**
  42549. * Uploads the updated texture data to the GPU.
  42550. *
  42551. * @param {Texture} texture - The texture.
  42552. * @param {Object} [options={}] - Optional configuration parameter.
  42553. */
  42554. updateTexture( texture, options ) {
  42555. const textureData = this.backend.get( texture );
  42556. const { textureDescriptorGPU } = textureData;
  42557. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42558. return;
  42559. // transfer texture data
  42560. if ( texture.isDataTexture ) {
  42561. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42562. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42563. for ( let i = 0; i < options.image.depth; i ++ ) {
  42564. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42565. }
  42566. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42567. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42568. } else if ( texture.isCubeTexture ) {
  42569. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42570. } else if ( texture.isVideoTexture ) {
  42571. const video = texture.source.data;
  42572. textureData.externalTexture = video;
  42573. } else {
  42574. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42575. }
  42576. //
  42577. textureData.version = texture.version;
  42578. if ( texture.onUpdate ) texture.onUpdate( texture );
  42579. }
  42580. /**
  42581. * Returns texture data as a typed array.
  42582. *
  42583. * @async
  42584. * @param {Texture} texture - The texture to copy.
  42585. * @param {Number} x - The x coordinate of the copy origin.
  42586. * @param {Number} y - The y coordinate of the copy origin.
  42587. * @param {Number} width - The width of the copy.
  42588. * @param {Number} height - The height of the copy.
  42589. * @param {Number} faceIndex - The face index.
  42590. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42591. */
  42592. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42593. const device = this.backend.device;
  42594. const textureData = this.backend.get( texture );
  42595. const textureGPU = textureData.texture;
  42596. const format = textureData.textureDescriptorGPU.format;
  42597. const bytesPerTexel = this._getBytesPerTexel( format );
  42598. let bytesPerRow = width * bytesPerTexel;
  42599. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42600. const readBuffer = device.createBuffer(
  42601. {
  42602. size: width * height * bytesPerTexel,
  42603. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42604. }
  42605. );
  42606. const encoder = device.createCommandEncoder();
  42607. encoder.copyTextureToBuffer(
  42608. {
  42609. texture: textureGPU,
  42610. origin: { x, y, z: faceIndex },
  42611. },
  42612. {
  42613. buffer: readBuffer,
  42614. bytesPerRow: bytesPerRow
  42615. },
  42616. {
  42617. width: width,
  42618. height: height
  42619. }
  42620. );
  42621. const typedArrayType = this._getTypedArrayType( format );
  42622. device.queue.submit( [ encoder.finish() ] );
  42623. await readBuffer.mapAsync( GPUMapMode.READ );
  42624. const buffer = readBuffer.getMappedRange();
  42625. return new typedArrayType( buffer );
  42626. }
  42627. /**
  42628. * Returns `true` if the given texture is an environment map.
  42629. *
  42630. * @private
  42631. * @param {Texture} texture - The texture.
  42632. * @return {Boolean} Whether the given texture is an environment map or not.
  42633. */
  42634. _isEnvironmentTexture( texture ) {
  42635. const mapping = texture.mapping;
  42636. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42637. }
  42638. /**
  42639. * Returns the default GPU texture for the given format.
  42640. *
  42641. * @private
  42642. * @param {String} format - The GPU format.
  42643. * @return {GPUTexture} The GPU texture.
  42644. */
  42645. _getDefaultTextureGPU( format ) {
  42646. let defaultTexture = this.defaultTexture[ format ];
  42647. if ( defaultTexture === undefined ) {
  42648. const texture = new Texture();
  42649. texture.minFilter = NearestFilter;
  42650. texture.magFilter = NearestFilter;
  42651. this.createTexture( texture, { width: 1, height: 1, format } );
  42652. this.defaultTexture[ format ] = defaultTexture = texture;
  42653. }
  42654. return this.backend.get( defaultTexture ).texture;
  42655. }
  42656. /**
  42657. * Returns the default GPU cube texture for the given format.
  42658. *
  42659. * @private
  42660. * @param {String} format - The GPU format.
  42661. * @return {GPUTexture} The GPU texture.
  42662. */
  42663. _getDefaultCubeTextureGPU( format ) {
  42664. let defaultCubeTexture = this.defaultTexture[ format ];
  42665. if ( defaultCubeTexture === undefined ) {
  42666. const texture = new CubeTexture();
  42667. texture.minFilter = NearestFilter;
  42668. texture.magFilter = NearestFilter;
  42669. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42670. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42671. }
  42672. return this.backend.get( defaultCubeTexture ).texture;
  42673. }
  42674. /**
  42675. * Returns the default video frame used as default data in context of video textures.
  42676. *
  42677. * @private
  42678. * @return {VideoFrame} The video frame.
  42679. */
  42680. _getDefaultVideoFrame() {
  42681. let defaultVideoFrame = this.defaultVideoFrame;
  42682. if ( defaultVideoFrame === null ) {
  42683. const init = {
  42684. timestamp: 0,
  42685. codedWidth: 1,
  42686. codedHeight: 1,
  42687. format: 'RGBA',
  42688. };
  42689. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42690. }
  42691. return defaultVideoFrame;
  42692. }
  42693. /**
  42694. * Uploads cube texture image data to the GPU memory.
  42695. *
  42696. * @private
  42697. * @param {Array} images - The cube image data.
  42698. * @param {GPUTexture} textureGPU - The GPU texture.
  42699. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42700. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42701. */
  42702. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42703. for ( let i = 0; i < 6; i ++ ) {
  42704. const image = images[ i ];
  42705. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42706. if ( image.isDataTexture ) {
  42707. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42708. } else {
  42709. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42710. }
  42711. }
  42712. }
  42713. /**
  42714. * Uploads texture image data to the GPU memory.
  42715. *
  42716. * @private
  42717. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  42718. * @param {GPUTexture} textureGPU - The GPU texture.
  42719. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42720. * @param {Number} originDepth - The origin depth.
  42721. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42722. */
  42723. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42724. const device = this.backend.device;
  42725. device.queue.copyExternalImageToTexture(
  42726. {
  42727. source: image,
  42728. flipY: flipY
  42729. }, {
  42730. texture: textureGPU,
  42731. mipLevel: 0,
  42732. origin: { x: 0, y: 0, z: originDepth }
  42733. }, {
  42734. width: image.width,
  42735. height: image.height,
  42736. depthOrArrayLayers: 1
  42737. }
  42738. );
  42739. }
  42740. /**
  42741. * Returns the pass utils singleton.
  42742. *
  42743. * @private
  42744. * @return {WebGPUTexturePassUtils} The utils instance.
  42745. */
  42746. _getPassUtils() {
  42747. let passUtils = this._passUtils;
  42748. if ( passUtils === null ) {
  42749. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42750. }
  42751. return passUtils;
  42752. }
  42753. /**
  42754. * Generates mipmaps for the given GPU texture.
  42755. *
  42756. * @private
  42757. * @param {GPUTexture} textureGPU - The GPU texture object.
  42758. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42759. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42760. */
  42761. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42762. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42763. }
  42764. /**
  42765. * Flip the contents of the given GPU texture along its vertical axis.
  42766. *
  42767. * @private
  42768. * @param {GPUTexture} textureGPU - The GPU texture object.
  42769. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42770. * @param {Number} [originDepth=0] - The origin depth.
  42771. */
  42772. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42773. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42774. }
  42775. /**
  42776. * Uploads texture buffer data to the GPU memory.
  42777. *
  42778. * @private
  42779. * @param {Object} image - An object defining the image buffer data.
  42780. * @param {GPUTexture} textureGPU - The GPU texture.
  42781. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42782. * @param {Number} originDepth - The origin depth.
  42783. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42784. * @param {Number} [depth=0] - TODO.
  42785. */
  42786. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42787. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42788. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42789. const device = this.backend.device;
  42790. const data = image.data;
  42791. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42792. const bytesPerRow = image.width * bytesPerTexel;
  42793. device.queue.writeTexture(
  42794. {
  42795. texture: textureGPU,
  42796. mipLevel: 0,
  42797. origin: { x: 0, y: 0, z: originDepth }
  42798. },
  42799. data,
  42800. {
  42801. offset: image.width * image.height * bytesPerTexel * depth,
  42802. bytesPerRow
  42803. },
  42804. {
  42805. width: image.width,
  42806. height: image.height,
  42807. depthOrArrayLayers: 1
  42808. } );
  42809. if ( flipY === true ) {
  42810. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42811. }
  42812. }
  42813. /**
  42814. * Uploads compressed texture data to the GPU memory.
  42815. *
  42816. * @private
  42817. * @param {Array<Object>} mipmaps - An array with mipmap data.
  42818. * @param {GPUTexture} textureGPU - The GPU texture.
  42819. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42820. */
  42821. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42822. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42823. const device = this.backend.device;
  42824. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42825. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42826. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42827. const mipmap = mipmaps[ i ];
  42828. const width = mipmap.width;
  42829. const height = mipmap.height;
  42830. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42831. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42832. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42833. for ( let j = 0; j < depth; j ++ ) {
  42834. device.queue.writeTexture(
  42835. {
  42836. texture: textureGPU,
  42837. mipLevel: i,
  42838. origin: { x: 0, y: 0, z: j }
  42839. },
  42840. mipmap.data,
  42841. {
  42842. offset: j * bytesPerImage,
  42843. bytesPerRow,
  42844. rowsPerImage: Math.ceil( height / blockData.height )
  42845. },
  42846. {
  42847. width: Math.ceil( width / blockData.width ) * blockData.width,
  42848. height: Math.ceil( height / blockData.height ) * blockData.height,
  42849. depthOrArrayLayers: 1
  42850. }
  42851. );
  42852. }
  42853. }
  42854. }
  42855. /**
  42856. * This method is only relevant for compressed texture formats. It returns a block
  42857. * data descriptor for the given GPU compressed texture format.
  42858. *
  42859. * @private
  42860. * @param {String} format - The GPU compressed texture format.
  42861. * @return {Object} The block data descriptor.
  42862. */
  42863. _getBlockData( format ) {
  42864. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42865. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42866. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42867. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42868. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42869. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42870. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42871. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42872. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42873. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42874. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42875. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42876. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42877. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42878. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42879. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42880. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42881. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42882. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42883. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42884. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42885. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42886. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42887. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42888. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42889. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42890. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42891. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42892. }
  42893. /**
  42894. * Converts the three.js uv wrapping constants to GPU address mode constants.
  42895. *
  42896. * @private
  42897. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  42898. * @return {String} The GPU address mode.
  42899. */
  42900. _convertAddressMode( value ) {
  42901. let addressMode = GPUAddressMode.ClampToEdge;
  42902. if ( value === RepeatWrapping ) {
  42903. addressMode = GPUAddressMode.Repeat;
  42904. } else if ( value === MirroredRepeatWrapping ) {
  42905. addressMode = GPUAddressMode.MirrorRepeat;
  42906. }
  42907. return addressMode;
  42908. }
  42909. /**
  42910. * Converts the three.js filter constants to GPU filter constants.
  42911. *
  42912. * @private
  42913. * @param {Number} value - The three.js constant defining a filter mode.
  42914. * @return {String} The GPU filter mode.
  42915. */
  42916. _convertFilterMode( value ) {
  42917. let filterMode = GPUFilterMode.Linear;
  42918. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42919. filterMode = GPUFilterMode.Nearest;
  42920. }
  42921. return filterMode;
  42922. }
  42923. /**
  42924. * Returns the bytes-per-texel value for the given GPU texture format.
  42925. *
  42926. * @private
  42927. * @param {String} format - The GPU texture format.
  42928. * @return {Number} The bytes-per-texel.
  42929. */
  42930. _getBytesPerTexel( format ) {
  42931. // 8-bit formats
  42932. if ( format === GPUTextureFormat.R8Unorm ||
  42933. format === GPUTextureFormat.R8Snorm ||
  42934. format === GPUTextureFormat.R8Uint ||
  42935. format === GPUTextureFormat.R8Sint ) return 1;
  42936. // 16-bit formats
  42937. if ( format === GPUTextureFormat.R16Uint ||
  42938. format === GPUTextureFormat.R16Sint ||
  42939. format === GPUTextureFormat.R16Float ||
  42940. format === GPUTextureFormat.RG8Unorm ||
  42941. format === GPUTextureFormat.RG8Snorm ||
  42942. format === GPUTextureFormat.RG8Uint ||
  42943. format === GPUTextureFormat.RG8Sint ) return 2;
  42944. // 32-bit formats
  42945. if ( format === GPUTextureFormat.R32Uint ||
  42946. format === GPUTextureFormat.R32Sint ||
  42947. format === GPUTextureFormat.R32Float ||
  42948. format === GPUTextureFormat.RG16Uint ||
  42949. format === GPUTextureFormat.RG16Sint ||
  42950. format === GPUTextureFormat.RG16Float ||
  42951. format === GPUTextureFormat.RGBA8Unorm ||
  42952. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42953. format === GPUTextureFormat.RGBA8Snorm ||
  42954. format === GPUTextureFormat.RGBA8Uint ||
  42955. format === GPUTextureFormat.RGBA8Sint ||
  42956. format === GPUTextureFormat.BGRA8Unorm ||
  42957. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42958. // Packed 32-bit formats
  42959. format === GPUTextureFormat.RGB9E5UFloat ||
  42960. format === GPUTextureFormat.RGB10A2Unorm ||
  42961. format === GPUTextureFormat.RG11B10UFloat ||
  42962. format === GPUTextureFormat.Depth32Float ||
  42963. format === GPUTextureFormat.Depth24Plus ||
  42964. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42965. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42966. // 64-bit formats
  42967. if ( format === GPUTextureFormat.RG32Uint ||
  42968. format === GPUTextureFormat.RG32Sint ||
  42969. format === GPUTextureFormat.RG32Float ||
  42970. format === GPUTextureFormat.RGBA16Uint ||
  42971. format === GPUTextureFormat.RGBA16Sint ||
  42972. format === GPUTextureFormat.RGBA16Float ) return 8;
  42973. // 128-bit formats
  42974. if ( format === GPUTextureFormat.RGBA32Uint ||
  42975. format === GPUTextureFormat.RGBA32Sint ||
  42976. format === GPUTextureFormat.RGBA32Float ) return 16;
  42977. }
  42978. /**
  42979. * Returns the corresponding typed array type for the given GPU texture format.
  42980. *
  42981. * @private
  42982. * @param {String} format - The GPU texture format.
  42983. * @return {TypedArray.constructor} The typed array type.
  42984. */
  42985. _getTypedArrayType( format ) {
  42986. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42987. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42988. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42989. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42990. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42991. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42992. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42993. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42994. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42995. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42996. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42997. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42998. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42999. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43000. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43001. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43002. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43003. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43004. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43005. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43006. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43007. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43008. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43009. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43010. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43011. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43012. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43013. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43014. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43015. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43016. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43017. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43018. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43019. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43020. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43021. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43022. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43023. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43024. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43025. }
  43026. /**
  43027. * Returns the GPU dimensions for the given texture.
  43028. *
  43029. * @private
  43030. * @param {Texture} texture - The texture.
  43031. * @return {String} The GPU dimension.
  43032. */
  43033. _getDimension( texture ) {
  43034. let dimension;
  43035. if ( texture.isData3DTexture ) {
  43036. dimension = GPUTextureDimension.ThreeD;
  43037. } else {
  43038. dimension = GPUTextureDimension.TwoD;
  43039. }
  43040. return dimension;
  43041. }
  43042. }
  43043. /**
  43044. * Returns the GPU format for the given texture.
  43045. *
  43046. * @param {Texture} texture - The texture.
  43047. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  43048. * It is not necessary to apply the device for most formats.
  43049. * @return {String} The GPU format.
  43050. */
  43051. function getFormat( texture, device = null ) {
  43052. const format = texture.format;
  43053. const type = texture.type;
  43054. const colorSpace = texture.colorSpace;
  43055. let formatGPU;
  43056. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43057. switch ( format ) {
  43058. case RGBA_S3TC_DXT1_Format:
  43059. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43060. break;
  43061. case RGBA_S3TC_DXT3_Format:
  43062. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43063. break;
  43064. case RGBA_S3TC_DXT5_Format:
  43065. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43066. break;
  43067. case RGB_ETC2_Format:
  43068. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43069. break;
  43070. case RGBA_ETC2_EAC_Format:
  43071. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43072. break;
  43073. case RGBA_ASTC_4x4_Format:
  43074. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43075. break;
  43076. case RGBA_ASTC_5x4_Format:
  43077. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43078. break;
  43079. case RGBA_ASTC_5x5_Format:
  43080. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43081. break;
  43082. case RGBA_ASTC_6x5_Format:
  43083. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43084. break;
  43085. case RGBA_ASTC_6x6_Format:
  43086. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43087. break;
  43088. case RGBA_ASTC_8x5_Format:
  43089. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43090. break;
  43091. case RGBA_ASTC_8x6_Format:
  43092. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43093. break;
  43094. case RGBA_ASTC_8x8_Format:
  43095. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43096. break;
  43097. case RGBA_ASTC_10x5_Format:
  43098. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43099. break;
  43100. case RGBA_ASTC_10x6_Format:
  43101. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43102. break;
  43103. case RGBA_ASTC_10x8_Format:
  43104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43105. break;
  43106. case RGBA_ASTC_10x10_Format:
  43107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43108. break;
  43109. case RGBA_ASTC_12x10_Format:
  43110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43111. break;
  43112. case RGBA_ASTC_12x12_Format:
  43113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43114. break;
  43115. case RGBAFormat:
  43116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43117. break;
  43118. default:
  43119. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43120. }
  43121. } else {
  43122. switch ( format ) {
  43123. case RGBAFormat:
  43124. switch ( type ) {
  43125. case ByteType:
  43126. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43127. break;
  43128. case ShortType:
  43129. formatGPU = GPUTextureFormat.RGBA16Sint;
  43130. break;
  43131. case UnsignedShortType:
  43132. formatGPU = GPUTextureFormat.RGBA16Uint;
  43133. break;
  43134. case UnsignedIntType:
  43135. formatGPU = GPUTextureFormat.RGBA32Uint;
  43136. break;
  43137. case IntType:
  43138. formatGPU = GPUTextureFormat.RGBA32Sint;
  43139. break;
  43140. case UnsignedByteType:
  43141. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43142. break;
  43143. case HalfFloatType:
  43144. formatGPU = GPUTextureFormat.RGBA16Float;
  43145. break;
  43146. case FloatType:
  43147. formatGPU = GPUTextureFormat.RGBA32Float;
  43148. break;
  43149. default:
  43150. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43151. }
  43152. break;
  43153. case RGBFormat:
  43154. switch ( type ) {
  43155. case UnsignedInt5999Type:
  43156. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43157. break;
  43158. default:
  43159. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43160. }
  43161. break;
  43162. case RedFormat:
  43163. switch ( type ) {
  43164. case ByteType:
  43165. formatGPU = GPUTextureFormat.R8Snorm;
  43166. break;
  43167. case ShortType:
  43168. formatGPU = GPUTextureFormat.R16Sint;
  43169. break;
  43170. case UnsignedShortType:
  43171. formatGPU = GPUTextureFormat.R16Uint;
  43172. break;
  43173. case UnsignedIntType:
  43174. formatGPU = GPUTextureFormat.R32Uint;
  43175. break;
  43176. case IntType:
  43177. formatGPU = GPUTextureFormat.R32Sint;
  43178. break;
  43179. case UnsignedByteType:
  43180. formatGPU = GPUTextureFormat.R8Unorm;
  43181. break;
  43182. case HalfFloatType:
  43183. formatGPU = GPUTextureFormat.R16Float;
  43184. break;
  43185. case FloatType:
  43186. formatGPU = GPUTextureFormat.R32Float;
  43187. break;
  43188. default:
  43189. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43190. }
  43191. break;
  43192. case RGFormat:
  43193. switch ( type ) {
  43194. case ByteType:
  43195. formatGPU = GPUTextureFormat.RG8Snorm;
  43196. break;
  43197. case ShortType:
  43198. formatGPU = GPUTextureFormat.RG16Sint;
  43199. break;
  43200. case UnsignedShortType:
  43201. formatGPU = GPUTextureFormat.RG16Uint;
  43202. break;
  43203. case UnsignedIntType:
  43204. formatGPU = GPUTextureFormat.RG32Uint;
  43205. break;
  43206. case IntType:
  43207. formatGPU = GPUTextureFormat.RG32Sint;
  43208. break;
  43209. case UnsignedByteType:
  43210. formatGPU = GPUTextureFormat.RG8Unorm;
  43211. break;
  43212. case HalfFloatType:
  43213. formatGPU = GPUTextureFormat.RG16Float;
  43214. break;
  43215. case FloatType:
  43216. formatGPU = GPUTextureFormat.RG32Float;
  43217. break;
  43218. default:
  43219. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43220. }
  43221. break;
  43222. case DepthFormat:
  43223. switch ( type ) {
  43224. case UnsignedShortType:
  43225. formatGPU = GPUTextureFormat.Depth16Unorm;
  43226. break;
  43227. case UnsignedIntType:
  43228. formatGPU = GPUTextureFormat.Depth24Plus;
  43229. break;
  43230. case FloatType:
  43231. formatGPU = GPUTextureFormat.Depth32Float;
  43232. break;
  43233. default:
  43234. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43235. }
  43236. break;
  43237. case DepthStencilFormat:
  43238. switch ( type ) {
  43239. case UnsignedInt248Type:
  43240. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43241. break;
  43242. case FloatType:
  43243. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43244. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43245. }
  43246. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43247. break;
  43248. default:
  43249. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43250. }
  43251. break;
  43252. case RedIntegerFormat:
  43253. switch ( type ) {
  43254. case IntType:
  43255. formatGPU = GPUTextureFormat.R32Sint;
  43256. break;
  43257. case UnsignedIntType:
  43258. formatGPU = GPUTextureFormat.R32Uint;
  43259. break;
  43260. default:
  43261. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43262. }
  43263. break;
  43264. case RGIntegerFormat:
  43265. switch ( type ) {
  43266. case IntType:
  43267. formatGPU = GPUTextureFormat.RG32Sint;
  43268. break;
  43269. case UnsignedIntType:
  43270. formatGPU = GPUTextureFormat.RG32Uint;
  43271. break;
  43272. default:
  43273. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43274. }
  43275. break;
  43276. case RGBAIntegerFormat:
  43277. switch ( type ) {
  43278. case IntType:
  43279. formatGPU = GPUTextureFormat.RGBA32Sint;
  43280. break;
  43281. case UnsignedIntType:
  43282. formatGPU = GPUTextureFormat.RGBA32Uint;
  43283. break;
  43284. default:
  43285. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43286. }
  43287. break;
  43288. default:
  43289. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43290. }
  43291. }
  43292. return formatGPU;
  43293. }
  43294. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43295. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43296. const wgslTypeLib$1 = {
  43297. 'f32': 'float',
  43298. 'i32': 'int',
  43299. 'u32': 'uint',
  43300. 'bool': 'bool',
  43301. 'vec2<f32>': 'vec2',
  43302. 'vec2<i32>': 'ivec2',
  43303. 'vec2<u32>': 'uvec2',
  43304. 'vec2<bool>': 'bvec2',
  43305. 'vec2f': 'vec2',
  43306. 'vec2i': 'ivec2',
  43307. 'vec2u': 'uvec2',
  43308. 'vec2b': 'bvec2',
  43309. 'vec3<f32>': 'vec3',
  43310. 'vec3<i32>': 'ivec3',
  43311. 'vec3<u32>': 'uvec3',
  43312. 'vec3<bool>': 'bvec3',
  43313. 'vec3f': 'vec3',
  43314. 'vec3i': 'ivec3',
  43315. 'vec3u': 'uvec3',
  43316. 'vec3b': 'bvec3',
  43317. 'vec4<f32>': 'vec4',
  43318. 'vec4<i32>': 'ivec4',
  43319. 'vec4<u32>': 'uvec4',
  43320. 'vec4<bool>': 'bvec4',
  43321. 'vec4f': 'vec4',
  43322. 'vec4i': 'ivec4',
  43323. 'vec4u': 'uvec4',
  43324. 'vec4b': 'bvec4',
  43325. 'mat2x2<f32>': 'mat2',
  43326. 'mat2x2f': 'mat2',
  43327. 'mat3x3<f32>': 'mat3',
  43328. 'mat3x3f': 'mat3',
  43329. 'mat4x4<f32>': 'mat4',
  43330. 'mat4x4f': 'mat4',
  43331. 'sampler': 'sampler',
  43332. 'texture_1d': 'texture',
  43333. 'texture_2d': 'texture',
  43334. 'texture_2d_array': 'texture',
  43335. 'texture_multisampled_2d': 'cubeTexture',
  43336. 'texture_depth_2d': 'depthTexture',
  43337. 'texture_depth_multisampled_2d': 'depthTexture',
  43338. 'texture_3d': 'texture3D',
  43339. 'texture_cube': 'cubeTexture',
  43340. 'texture_cube_array': 'cubeTexture',
  43341. 'texture_storage_1d': 'storageTexture',
  43342. 'texture_storage_2d': 'storageTexture',
  43343. 'texture_storage_2d_array': 'storageTexture',
  43344. 'texture_storage_3d': 'storageTexture'
  43345. };
  43346. const parse = ( source ) => {
  43347. source = source.trim();
  43348. const declaration = source.match( declarationRegexp );
  43349. if ( declaration !== null && declaration.length === 4 ) {
  43350. const inputsCode = declaration[ 2 ];
  43351. const propsMatches = [];
  43352. let match = null;
  43353. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43354. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43355. }
  43356. // Process matches to correctly pair names and types
  43357. const inputs = [];
  43358. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43359. const { name, type } = propsMatches[ i ];
  43360. let resolvedType = type;
  43361. if ( resolvedType.startsWith( 'ptr' ) ) {
  43362. resolvedType = 'pointer';
  43363. } else {
  43364. if ( resolvedType.startsWith( 'texture' ) ) {
  43365. resolvedType = type.split( '<' )[ 0 ];
  43366. }
  43367. resolvedType = wgslTypeLib$1[ resolvedType ];
  43368. }
  43369. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43370. }
  43371. const blockCode = source.substring( declaration[ 0 ].length );
  43372. const outputType = declaration[ 3 ] || 'void';
  43373. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43374. const type = wgslTypeLib$1[ outputType ] || outputType;
  43375. return {
  43376. type,
  43377. inputs,
  43378. name,
  43379. inputsCode,
  43380. blockCode,
  43381. outputType
  43382. };
  43383. } else {
  43384. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43385. }
  43386. };
  43387. /**
  43388. * This class represents a WSL node function.
  43389. *
  43390. * @augments NodeFunction
  43391. */
  43392. class WGSLNodeFunction extends NodeFunction {
  43393. /**
  43394. * Constructs a new WGSL node function.
  43395. *
  43396. * @param {String} source - The WGSL source.
  43397. */
  43398. constructor( source ) {
  43399. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43400. super( type, inputs, name );
  43401. this.inputsCode = inputsCode;
  43402. this.blockCode = blockCode;
  43403. this.outputType = outputType;
  43404. }
  43405. /**
  43406. * This method returns the WGSL code of the node function.
  43407. *
  43408. * @param {String} [name=this.name] - The function's name.
  43409. * @return {String} The shader code.
  43410. */
  43411. getCode( name = this.name ) {
  43412. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43413. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43414. }
  43415. }
  43416. /**
  43417. * A WGSL node parser.
  43418. *
  43419. * @augments NodeParser
  43420. */
  43421. class WGSLNodeParser extends NodeParser {
  43422. /**
  43423. * The method parses the given WGSL code an returns a node function.
  43424. *
  43425. * @param {String} source - The WGSL code.
  43426. * @return {WGSLNodeFunction} A node function.
  43427. */
  43428. parseFunction( source ) {
  43429. return new WGSLNodeFunction( source );
  43430. }
  43431. }
  43432. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43433. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  43434. const accessNames = {
  43435. [ NodeAccess.READ_ONLY ]: 'read',
  43436. [ NodeAccess.WRITE_ONLY ]: 'write',
  43437. [ NodeAccess.READ_WRITE ]: 'read_write'
  43438. };
  43439. const wrapNames = {
  43440. [ RepeatWrapping ]: 'repeat',
  43441. [ ClampToEdgeWrapping ]: 'clamp',
  43442. [ MirroredRepeatWrapping ]: 'mirror'
  43443. };
  43444. const gpuShaderStageLib = {
  43445. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43446. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43447. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43448. };
  43449. const supports = {
  43450. instance: true,
  43451. swizzleAssign: false,
  43452. storageBuffer: true
  43453. };
  43454. const wgslFnOpLib = {
  43455. '^^': 'tsl_xor'
  43456. };
  43457. const wgslTypeLib = {
  43458. float: 'f32',
  43459. int: 'i32',
  43460. uint: 'u32',
  43461. bool: 'bool',
  43462. color: 'vec3<f32>',
  43463. vec2: 'vec2<f32>',
  43464. ivec2: 'vec2<i32>',
  43465. uvec2: 'vec2<u32>',
  43466. bvec2: 'vec2<bool>',
  43467. vec3: 'vec3<f32>',
  43468. ivec3: 'vec3<i32>',
  43469. uvec3: 'vec3<u32>',
  43470. bvec3: 'vec3<bool>',
  43471. vec4: 'vec4<f32>',
  43472. ivec4: 'vec4<i32>',
  43473. uvec4: 'vec4<u32>',
  43474. bvec4: 'vec4<bool>',
  43475. mat2: 'mat2x2<f32>',
  43476. mat3: 'mat3x3<f32>',
  43477. mat4: 'mat4x4<f32>'
  43478. };
  43479. const wgslCodeCache = {};
  43480. const wgslPolyfill = {
  43481. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43482. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43483. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43484. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43485. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43486. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43487. 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 ); }' ),
  43488. 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 ); }' ),
  43489. 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 ); }' ),
  43490. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  43491. 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 ); }' ),
  43492. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  43493. biquadraticTexture: new CodeNode( /* wgsl */`
  43494. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  43495. let res = vec2f( iRes );
  43496. let uvScaled = coord * res;
  43497. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43498. // https://www.shadertoy.com/view/WtyXRy
  43499. let uv = uvWrapping - 0.5;
  43500. let iuv = floor( uv );
  43501. let f = fract( uv );
  43502. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  43503. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  43504. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  43505. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  43506. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43507. }
  43508. ` )
  43509. };
  43510. const wgslMethods = {
  43511. dFdx: 'dpdx',
  43512. dFdy: '- dpdy',
  43513. mod_float: 'tsl_mod_float',
  43514. mod_vec2: 'tsl_mod_vec2',
  43515. mod_vec3: 'tsl_mod_vec3',
  43516. mod_vec4: 'tsl_mod_vec4',
  43517. equals_bool: 'tsl_equals_bool',
  43518. equals_bvec2: 'tsl_equals_bvec2',
  43519. equals_bvec3: 'tsl_equals_bvec3',
  43520. equals_bvec4: 'tsl_equals_bvec4',
  43521. inversesqrt: 'inverseSqrt',
  43522. bitcast: 'bitcast<f32>'
  43523. };
  43524. // WebGPU issue: does not support pow() with negative base on Windows
  43525. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  43526. 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 ); }' );
  43527. 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 ] );
  43528. 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 ] );
  43529. 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 ] );
  43530. wgslMethods.pow_float = 'tsl_pow_float';
  43531. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43532. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43533. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43534. }
  43535. //
  43536. let diagnostics = '';
  43537. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  43538. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43539. }
  43540. /**
  43541. * A node builder targeting WGSL.
  43542. *
  43543. * This module generates WGSL shader code from node materials and also
  43544. * generates the respective bindings and vertex buffer definitions. These
  43545. * data are later used by the renderer to create render and compute pipelines
  43546. * for render objects.
  43547. *
  43548. * @augments NodeBuilder
  43549. */
  43550. class WGSLNodeBuilder extends NodeBuilder {
  43551. /**
  43552. * Constructs a new WGSL node builder renderer.
  43553. *
  43554. * @param {Object3D} object - The 3D object.
  43555. * @param {Renderer} renderer - The renderer.
  43556. */
  43557. constructor( object, renderer ) {
  43558. super( object, renderer, new WGSLNodeParser() );
  43559. /**
  43560. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  43561. * another dictionary which manages UBOs per group ('render','frame','object').
  43562. *
  43563. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  43564. */
  43565. this.uniformGroups = {};
  43566. /**
  43567. * A dictionary that holds for each shader stage a Map of builtins.
  43568. *
  43569. * @type {Object<String,Map<String,Object>>}
  43570. */
  43571. this.builtins = {};
  43572. /**
  43573. * A dictionary that holds for each shader stage a Set of directives.
  43574. *
  43575. * @type {Object<String,Set<String>>}
  43576. */
  43577. this.directives = {};
  43578. /**
  43579. * A map for managing scope arrays. Only relevant for when using
  43580. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  43581. *
  43582. * @type {Map<String,Object>}
  43583. */
  43584. this.scopedArrays = new Map();
  43585. }
  43586. /**
  43587. * Checks if the given texture requires a manual conversion to the working color space.
  43588. *
  43589. * @param {Texture} texture - The texture to check.
  43590. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  43591. */
  43592. needsToWorkingColorSpace( texture ) {
  43593. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43594. }
  43595. /**
  43596. * Generates the WGSL snippet for sampled textures.
  43597. *
  43598. * @private
  43599. * @param {Texture} texture - The texture.
  43600. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43601. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43602. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43603. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43604. * @return {String} The WGSL snippet.
  43605. */
  43606. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43607. if ( shaderStage === 'fragment' ) {
  43608. if ( depthSnippet ) {
  43609. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43610. } else {
  43611. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43612. }
  43613. } else if ( this.isFilteredTexture( texture ) ) {
  43614. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43615. } else {
  43616. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  43617. }
  43618. }
  43619. /**
  43620. * Generates the WGSL snippet when sampling video textures.
  43621. *
  43622. * @private
  43623. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43624. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43625. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43626. * @return {String} The WGSL snippet.
  43627. */
  43628. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43629. if ( shaderStage === 'fragment' ) {
  43630. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43631. } else {
  43632. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43633. }
  43634. }
  43635. /**
  43636. * Generates the WGSL snippet when sampling textures with explicit mip level.
  43637. *
  43638. * @private
  43639. * @param {Texture} texture - The texture.
  43640. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43641. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43642. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43643. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43644. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43645. * @return {String} The WGSL snippet.
  43646. */
  43647. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43648. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  43649. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43650. } else if ( this.isFilteredTexture( texture ) ) {
  43651. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43652. } else {
  43653. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  43654. }
  43655. }
  43656. /**
  43657. * Generates a wrap function used in context of textures.
  43658. *
  43659. * @param {Texture} texture - The texture to generate the function for.
  43660. * @return {String} The name of the generated function.
  43661. */
  43662. generateWrapFunction( texture ) {
  43663. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  43664. let nodeCode = wgslCodeCache[ functionName ];
  43665. if ( nodeCode === undefined ) {
  43666. const includes = [];
  43667. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  43668. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  43669. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  43670. const addWrapSnippet = ( wrap, axis ) => {
  43671. if ( wrap === RepeatWrapping ) {
  43672. includes.push( wgslPolyfill.repeatWrapping_float );
  43673. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  43674. } else if ( wrap === ClampToEdgeWrapping ) {
  43675. includes.push( wgslPolyfill.clampWrapping_float );
  43676. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  43677. } else if ( wrap === MirroredRepeatWrapping ) {
  43678. includes.push( wgslPolyfill.mirrorWrapping_float );
  43679. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  43680. } else {
  43681. code += `\t\tcoord.${ axis }`;
  43682. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  43683. }
  43684. };
  43685. addWrapSnippet( texture.wrapS, 'x' );
  43686. code += ',\n';
  43687. addWrapSnippet( texture.wrapT, 'y' );
  43688. if ( texture.isData3DTexture ) {
  43689. code += ',\n';
  43690. addWrapSnippet( texture.wrapR, 'z' );
  43691. }
  43692. code += '\n\t);\n\n}\n';
  43693. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  43694. }
  43695. nodeCode.build( this );
  43696. return functionName;
  43697. }
  43698. /**
  43699. * Generates a WGSL variable that holds the texture dimension of the given texture.
  43700. * It also returns information about the the number of layers (elements) of an arrayed
  43701. * texture as well as the cube face count of cube textures.
  43702. *
  43703. * @param {Texture} texture - The texture to generate the function for.
  43704. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43705. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43706. * @return {String} The name of the dimension variable.
  43707. */
  43708. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  43709. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  43710. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  43711. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  43712. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  43713. let textureDimensionsParams;
  43714. let dimensionType;
  43715. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  43716. const isMultisampled = primarySamples > 1;
  43717. if ( texture.isData3DTexture ) {
  43718. dimensionType = 'vec3<u32>';
  43719. } else {
  43720. // Regular 2D textures, depth textures, etc.
  43721. dimensionType = 'vec2<u32>';
  43722. }
  43723. // Build parameters string based on texture type and multisampling
  43724. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  43725. textureDimensionsParams = textureProperty;
  43726. } else {
  43727. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  43728. }
  43729. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  43730. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  43731. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43732. textureData.arrayLayerCount = new VarNode(
  43733. new ExpressionNode(
  43734. `textureNumLayers(${textureProperty})`,
  43735. 'u32'
  43736. )
  43737. );
  43738. }
  43739. // For cube textures, we know it's always 6 faces
  43740. if ( texture.isTextureCube ) {
  43741. textureData.cubeFaceCount = new VarNode(
  43742. new ExpressionNode( '6u', 'u32' )
  43743. );
  43744. }
  43745. }
  43746. return textureDimensionNode.build( this );
  43747. }
  43748. /**
  43749. * Generates the WGSL snippet for a manual filtered texture.
  43750. *
  43751. * @param {Texture} texture - The texture.
  43752. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43753. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43754. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43755. * @return {String} The WGSL snippet.
  43756. */
  43757. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  43758. this._include( 'biquadraticTexture' );
  43759. const wrapFunction = this.generateWrapFunction( texture );
  43760. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43761. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  43762. }
  43763. /**
  43764. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  43765. * Since it's a lookup, no sampling or filtering is applied.
  43766. *
  43767. * @param {Texture} texture - The texture.
  43768. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43769. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43770. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43771. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43772. * @return {String} The WGSL snippet.
  43773. */
  43774. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  43775. const wrapFunction = this.generateWrapFunction( texture );
  43776. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43777. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  43778. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  43779. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  43780. }
  43781. /**
  43782. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  43783. *
  43784. * @param {Texture} texture - The texture.
  43785. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43786. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43787. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43788. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43789. * @return {String} The WGSL snippet.
  43790. */
  43791. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43792. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  43793. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  43794. } else if ( depthSnippet ) {
  43795. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  43796. } else {
  43797. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  43798. }
  43799. }
  43800. /**
  43801. * Generates the WGSL snippet that writes a single texel to a texture.
  43802. *
  43803. * @param {Texture} texture - The texture.
  43804. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43805. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43806. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  43807. * @return {String} The WGSL snippet.
  43808. */
  43809. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43810. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43811. }
  43812. /**
  43813. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  43814. *
  43815. * @param {Texture} texture - The texture.
  43816. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  43817. */
  43818. isSampleCompare( texture ) {
  43819. return texture.isDepthTexture === true && texture.compareFunction !== null;
  43820. }
  43821. /**
  43822. * Returns `true` if the given texture is unfilterable.
  43823. *
  43824. * @param {Texture} texture - The texture.
  43825. * @return {Boolean} Whether the given texture is unfilterable or not.
  43826. */
  43827. isUnfilterable( texture ) {
  43828. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  43829. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  43830. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  43831. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  43832. }
  43833. /**
  43834. * Generates the WGSL snippet for sampling/loading the given texture.
  43835. *
  43836. * @param {Texture} texture - The texture.
  43837. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43838. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43839. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43840. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43841. * @return {String} The WGSL snippet.
  43842. */
  43843. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43844. let snippet = null;
  43845. if ( texture.isVideoTexture === true ) {
  43846. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43847. } else if ( this.isUnfilterable( texture ) ) {
  43848. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  43849. } else {
  43850. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43851. }
  43852. return snippet;
  43853. }
  43854. /**
  43855. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  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 {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  43861. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43862. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43863. * @return {String} The WGSL snippet.
  43864. */
  43865. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43866. if ( shaderStage === 'fragment' ) {
  43867. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43868. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43869. } else {
  43870. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43871. }
  43872. }
  43873. /**
  43874. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  43875. * against a reference value.
  43876. *
  43877. * @param {Texture} texture - The texture.
  43878. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43879. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43880. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  43881. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43882. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43883. * @return {String} The WGSL snippet.
  43884. */
  43885. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43886. if ( shaderStage === 'fragment' ) {
  43887. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43888. } else {
  43889. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43890. }
  43891. }
  43892. /**
  43893. * Generates the WGSL snippet when sampling textures with explicit mip level.
  43894. *
  43895. * @param {Texture} texture - The texture.
  43896. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43897. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43898. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43899. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43900. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43901. * @return {String} The WGSL snippet.
  43902. */
  43903. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43904. let snippet = null;
  43905. if ( texture.isVideoTexture === true ) {
  43906. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43907. } else {
  43908. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43909. }
  43910. return snippet;
  43911. }
  43912. /**
  43913. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  43914. *
  43915. * @param {Texture} texture - The texture.
  43916. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43917. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43918. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  43919. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43920. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43921. * @return {String} The WGSL snippet.
  43922. */
  43923. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43924. if ( shaderStage === 'fragment' ) {
  43925. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43926. } else {
  43927. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43928. }
  43929. }
  43930. /**
  43931. * Returns a WGSL snippet that represents the property name of the given node.
  43932. *
  43933. * @param {Node} node - The node.
  43934. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43935. * @return {String} The property name.
  43936. */
  43937. getPropertyName( node, shaderStage = this.shaderStage ) {
  43938. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43939. if ( shaderStage === 'vertex' ) {
  43940. return `varyings.${ node.name }`;
  43941. }
  43942. } else if ( node.isNodeUniform === true ) {
  43943. const name = node.name;
  43944. const type = node.type;
  43945. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43946. return name;
  43947. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43948. return `NodeBuffer_${ node.id }.${name}`;
  43949. } else {
  43950. return node.groupNode.name + '.' + name;
  43951. }
  43952. }
  43953. return super.getPropertyName( node );
  43954. }
  43955. /**
  43956. * Returns the output struct name.
  43957. *
  43958. * @return {String} The name of the output struct.
  43959. */
  43960. getOutputStructName() {
  43961. return 'output';
  43962. }
  43963. /**
  43964. * Returns uniforms group count for the given shader stage.
  43965. *
  43966. * @private
  43967. * @param {String} shaderStage - The shader stage.
  43968. * @return {Number} The uniforms group count for the given shader stage.
  43969. */
  43970. _getUniformGroupCount( shaderStage ) {
  43971. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43972. }
  43973. /**
  43974. * Returns the native shader operator name for a given generic name.
  43975. *
  43976. * @param {String} op - The operator name to resolve.
  43977. * @return {String} The resolved operator name.
  43978. */
  43979. getFunctionOperator( op ) {
  43980. const fnOp = wgslFnOpLib[ op ];
  43981. if ( fnOp !== undefined ) {
  43982. this._include( fnOp );
  43983. return fnOp;
  43984. }
  43985. return null;
  43986. }
  43987. /**
  43988. * Returns the node access for the given node and shader stage.
  43989. *
  43990. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  43991. * @param {String} shaderStage - The shader stage.
  43992. * @return {String} The node access.
  43993. */
  43994. getNodeAccess( node, shaderStage ) {
  43995. if ( shaderStage !== 'compute' )
  43996. return NodeAccess.READ_ONLY;
  43997. return node.access;
  43998. }
  43999. /**
  44000. * Returns A WGSL snippet representing the storage access.
  44001. *
  44002. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44003. * @param {String} shaderStage - The shader stage.
  44004. * @return {String} The WGSL snippet representing the storage access.
  44005. */
  44006. getStorageAccess( node, shaderStage ) {
  44007. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  44008. }
  44009. /**
  44010. * This method is one of the more important ones since it's responsible
  44011. * for generating a matching binding instance for the given uniform node.
  44012. *
  44013. * These bindings are later used in the renderer to create bind groups
  44014. * and layouts.
  44015. *
  44016. * @param {UniformNode} node - The uniform node.
  44017. * @param {String} type - The node data type.
  44018. * @param {String} shaderStage - The shader stage.
  44019. * @param {String?} [name=null] - An optional uniform name.
  44020. * @return {NodeUniform} The node uniform object.
  44021. */
  44022. getUniformFromNode( node, type, shaderStage, name = null ) {
  44023. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44024. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44025. if ( nodeData.uniformGPU === undefined ) {
  44026. let uniformGPU;
  44027. const group = node.groupNode;
  44028. const groupName = group.name;
  44029. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44030. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44031. let texture = null;
  44032. const access = this.getNodeAccess( node, shaderStage );
  44033. if ( type === 'texture' || type === 'storageTexture' ) {
  44034. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  44035. } else if ( type === 'cubeTexture' ) {
  44036. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  44037. } else if ( type === 'texture3D' ) {
  44038. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  44039. }
  44040. texture.store = node.isStorageTextureNode === true;
  44041. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44042. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44043. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44044. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44045. bindings.push( sampler, texture );
  44046. uniformGPU = [ sampler, texture ];
  44047. } else {
  44048. bindings.push( texture );
  44049. uniformGPU = [ texture ];
  44050. }
  44051. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44052. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  44053. const buffer = new bufferClass( node, group );
  44054. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44055. bindings.push( buffer );
  44056. uniformGPU = buffer;
  44057. } else {
  44058. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44059. let uniformsGroup = uniformsStage[ groupName ];
  44060. if ( uniformsGroup === undefined ) {
  44061. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44062. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44063. uniformsStage[ groupName ] = uniformsGroup;
  44064. bindings.push( uniformsGroup );
  44065. }
  44066. uniformGPU = this.getNodeUniform( uniformNode, type );
  44067. uniformsGroup.addUniform( uniformGPU );
  44068. }
  44069. nodeData.uniformGPU = uniformGPU;
  44070. }
  44071. return uniformNode;
  44072. }
  44073. /**
  44074. * This method should be used whenever builtins are required in nodes.
  44075. * The internal builtins data structure will make sure builtins are
  44076. * defined in the WGSL source.
  44077. *
  44078. * @param {String} name - The builtin name.
  44079. * @param {String} property - The property name.
  44080. * @param {String} type - The node data type.
  44081. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44082. * @return {String} The property name.
  44083. */
  44084. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44085. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44086. if ( map.has( name ) === false ) {
  44087. map.set( name, {
  44088. name,
  44089. property,
  44090. type
  44091. } );
  44092. }
  44093. return property;
  44094. }
  44095. /**
  44096. * Returns `true` if the given builtin is defined in the given shader stage.
  44097. *
  44098. * @param {String} name - The builtin name.
  44099. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44100. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  44101. */
  44102. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44103. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44104. }
  44105. /**
  44106. * Returns the vertex index builtin.
  44107. *
  44108. * @return {String} The vertex index.
  44109. */
  44110. getVertexIndex() {
  44111. if ( this.shaderStage === 'vertex' ) {
  44112. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44113. }
  44114. return 'vertexIndex';
  44115. }
  44116. /**
  44117. * Builds the given shader node.
  44118. *
  44119. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44120. * @return {String} The WGSL function code.
  44121. */
  44122. buildFunctionCode( shaderNode ) {
  44123. const layout = shaderNode.layout;
  44124. const flowData = this.flowShaderNode( shaderNode );
  44125. const parameters = [];
  44126. for ( const input of layout.inputs ) {
  44127. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44128. }
  44129. //
  44130. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44131. ${ flowData.vars }
  44132. ${ flowData.code }
  44133. `;
  44134. if ( flowData.result ) {
  44135. code += `\treturn ${ flowData.result };\n`;
  44136. }
  44137. code += '\n}\n';
  44138. //
  44139. return code;
  44140. }
  44141. /**
  44142. * Returns the instance index builtin.
  44143. *
  44144. * @return {String} The instance index.
  44145. */
  44146. getInstanceIndex() {
  44147. if ( this.shaderStage === 'vertex' ) {
  44148. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44149. }
  44150. return 'instanceIndex';
  44151. }
  44152. /**
  44153. * Returns the invocation local index builtin.
  44154. *
  44155. * @return {String} The invocation local index.
  44156. */
  44157. getInvocationLocalIndex() {
  44158. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44159. }
  44160. /**
  44161. * Returns the subgroup size builtin.
  44162. *
  44163. * @return {String} The subgroup size.
  44164. */
  44165. getSubgroupSize() {
  44166. this.enableSubGroups();
  44167. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44168. }
  44169. /**
  44170. * Returns the invocation subgroup index builtin.
  44171. *
  44172. * @return {String} The invocation subgroup index.
  44173. */
  44174. getInvocationSubgroupIndex() {
  44175. this.enableSubGroups();
  44176. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44177. }
  44178. /**
  44179. * Returns the subgroup index builtin.
  44180. *
  44181. * @return {String} The subgroup index.
  44182. */
  44183. getSubgroupIndex() {
  44184. this.enableSubGroups();
  44185. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44186. }
  44187. /**
  44188. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  44189. *
  44190. * @return {null} Null.
  44191. */
  44192. getDrawIndex() {
  44193. return null;
  44194. }
  44195. /**
  44196. * Returns the front facing builtin.
  44197. *
  44198. * @return {String} The front facing builtin.
  44199. */
  44200. getFrontFacing() {
  44201. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44202. }
  44203. /**
  44204. * Returns the frag coord builtin.
  44205. *
  44206. * @return {String} The frag coord builtin.
  44207. */
  44208. getFragCoord() {
  44209. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44210. }
  44211. /**
  44212. * Returns the frag depth builtin.
  44213. *
  44214. * @return {String} The frag depth builtin.
  44215. */
  44216. getFragDepth() {
  44217. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44218. }
  44219. /**
  44220. * Returns the clip distances builtin.
  44221. *
  44222. * @return {String} The clip distances builtin.
  44223. */
  44224. getClipDistance() {
  44225. return 'varyings.hw_clip_distances';
  44226. }
  44227. /**
  44228. * Whether to flip texture data along its vertical axis or not.
  44229. *
  44230. * @return {Boolean} Returns always `false` in context of WGSL.
  44231. */
  44232. isFlipY() {
  44233. return false;
  44234. }
  44235. /**
  44236. * Enables the given directive for the given shader stage.
  44237. *
  44238. * @param {String} name - The directive name.
  44239. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  44240. */
  44241. enableDirective( name, shaderStage = this.shaderStage ) {
  44242. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44243. stage.add( name );
  44244. }
  44245. /**
  44246. * Returns the directives of the given shader stage as a WGSL string.
  44247. *
  44248. * @param {String} shaderStage - The shader stage.
  44249. * @return {String} A WGSL snippet that enables the directives of the given stage.
  44250. */
  44251. getDirectives( shaderStage ) {
  44252. const snippets = [];
  44253. const directives = this.directives[ shaderStage ];
  44254. if ( directives !== undefined ) {
  44255. for ( const directive of directives ) {
  44256. snippets.push( `enable ${directive};` );
  44257. }
  44258. }
  44259. return snippets.join( '\n' );
  44260. }
  44261. /**
  44262. * Enables the 'subgroups' directive.
  44263. */
  44264. enableSubGroups() {
  44265. this.enableDirective( 'subgroups' );
  44266. }
  44267. /**
  44268. * Enables the 'subgroups-f16' directive.
  44269. */
  44270. enableSubgroupsF16() {
  44271. this.enableDirective( 'subgroups-f16' );
  44272. }
  44273. /**
  44274. * Enables the 'clip_distances' directive.
  44275. */
  44276. enableClipDistances() {
  44277. this.enableDirective( 'clip_distances' );
  44278. }
  44279. /**
  44280. * Enables the 'f16' directive.
  44281. */
  44282. enableShaderF16() {
  44283. this.enableDirective( 'f16' );
  44284. }
  44285. /**
  44286. * Enables the 'dual_source_blending' directive.
  44287. */
  44288. enableDualSourceBlending() {
  44289. this.enableDirective( 'dual_source_blending' );
  44290. }
  44291. /**
  44292. * Enables hardware clipping.
  44293. *
  44294. * @param {String} planeCount - The clipping plane count.
  44295. */
  44296. enableHardwareClipping( planeCount ) {
  44297. this.enableClipDistances();
  44298. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  44299. }
  44300. /**
  44301. * Returns the builtins of the given shader stage as a WGSL string.
  44302. *
  44303. * @param {String} shaderStage - The shader stage.
  44304. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  44305. */
  44306. getBuiltins( shaderStage ) {
  44307. const snippets = [];
  44308. const builtins = this.builtins[ shaderStage ];
  44309. if ( builtins !== undefined ) {
  44310. for ( const { name, property, type } of builtins.values() ) {
  44311. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44312. }
  44313. }
  44314. return snippets.join( ',\n\t' );
  44315. }
  44316. /**
  44317. * This method should be used when a new scoped buffer is used in context of
  44318. * compute shaders. It adds the array to the internal data structure which is
  44319. * later used to generate the respective WGSL.
  44320. *
  44321. * @param {String} name - The array name.
  44322. * @param {String} scope - The scope.
  44323. * @param {String} bufferType - The buffer type.
  44324. * @param {String} bufferCount - The buffer count.
  44325. * @return {String} The array name.
  44326. */
  44327. getScopedArray( name, scope, bufferType, bufferCount ) {
  44328. if ( this.scopedArrays.has( name ) === false ) {
  44329. this.scopedArrays.set( name, {
  44330. name,
  44331. scope,
  44332. bufferType,
  44333. bufferCount
  44334. } );
  44335. }
  44336. return name;
  44337. }
  44338. /**
  44339. * Returns the scoped arrays of the given shader stage as a WGSL string.
  44340. *
  44341. * @param {String} shaderStage - The shader stage.
  44342. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  44343. * Returns `undefined` when used in the vertex or fragment stage.
  44344. */
  44345. getScopedArrays( shaderStage ) {
  44346. if ( shaderStage !== 'compute' ) {
  44347. return;
  44348. }
  44349. const snippets = [];
  44350. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  44351. const type = this.getType( bufferType );
  44352. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  44353. }
  44354. return snippets.join( '\n' );
  44355. }
  44356. /**
  44357. * Returns the shader attributes of the given shader stage as a WGSL string.
  44358. *
  44359. * @param {String} shaderStage - The shader stage.
  44360. * @return {String} The WGSL snippet that defines the shader attributes.
  44361. */
  44362. getAttributes( shaderStage ) {
  44363. const snippets = [];
  44364. if ( shaderStage === 'compute' ) {
  44365. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  44366. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  44367. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  44368. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  44369. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  44370. this.enableDirective( 'subgroups', shaderStage );
  44371. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44372. }
  44373. }
  44374. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44375. const builtins = this.getBuiltins( 'attribute' );
  44376. if ( builtins ) snippets.push( builtins );
  44377. const attributes = this.getAttributesArray();
  44378. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  44379. const attribute = attributes[ index ];
  44380. const name = attribute.name;
  44381. const type = this.getType( attribute.type );
  44382. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  44383. }
  44384. }
  44385. return snippets.join( ',\n\t' );
  44386. }
  44387. /**
  44388. * Returns the members of the given struct type node as a WGSL string.
  44389. *
  44390. * @param {StructTypeNode} struct - The struct type node.
  44391. * @return {String} The WGSL snippet that defines the struct members.
  44392. */
  44393. getStructMembers( struct ) {
  44394. const snippets = [];
  44395. const members = struct.getMemberTypes();
  44396. for ( let i = 0; i < members.length; i ++ ) {
  44397. const member = members[ i ];
  44398. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  44399. }
  44400. const builtins = this.getBuiltins( 'output' );
  44401. if ( builtins ) snippets.push( '\t' + builtins );
  44402. return snippets.join( ',\n' );
  44403. }
  44404. /**
  44405. * Returns the structs of the given shader stage as a WGSL string.
  44406. *
  44407. * @param {String} shaderStage - The shader stage.
  44408. * @return {String} The WGSL snippet that defines the structs.
  44409. */
  44410. getStructs( shaderStage ) {
  44411. const snippets = [];
  44412. const structs = this.structs[ shaderStage ];
  44413. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  44414. const struct = structs[ index ];
  44415. const name = struct.name;
  44416. let snippet = `\struct ${ name } {\n`;
  44417. snippet += this.getStructMembers( struct );
  44418. snippet += '\n}';
  44419. snippets.push( snippet );
  44420. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  44421. }
  44422. return snippets.join( '\n\n' );
  44423. }
  44424. /**
  44425. * Returns a WGSL string representing a variable.
  44426. *
  44427. * @param {String} type - The variable's type.
  44428. * @param {String} name - The variable's name.
  44429. * @return {String} The WGSL snippet that defines a variable.
  44430. */
  44431. getVar( type, name ) {
  44432. return `var ${ name } : ${ this.getType( type ) }`;
  44433. }
  44434. /**
  44435. * Returns the variables of the given shader stage as a WGSL string.
  44436. *
  44437. * @param {String} shaderStage - The shader stage.
  44438. * @return {String} The WGSL snippet that defines the variables.
  44439. */
  44440. getVars( shaderStage ) {
  44441. const snippets = [];
  44442. const vars = this.vars[ shaderStage ];
  44443. if ( vars !== undefined ) {
  44444. for ( const variable of vars ) {
  44445. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  44446. }
  44447. }
  44448. return `\n${ snippets.join( '\n' ) }\n`;
  44449. }
  44450. /**
  44451. * Returns the varyings of the given shader stage as a WGSL string.
  44452. *
  44453. * @param {String} shaderStage - The shader stage.
  44454. * @return {String} The WGSL snippet that defines the varyings.
  44455. */
  44456. getVaryings( shaderStage ) {
  44457. const snippets = [];
  44458. if ( shaderStage === 'vertex' ) {
  44459. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  44460. }
  44461. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  44462. const varyings = this.varyings;
  44463. const vars = this.vars[ shaderStage ];
  44464. for ( let index = 0; index < varyings.length; index ++ ) {
  44465. const varying = varyings[ index ];
  44466. if ( varying.needsInterpolation ) {
  44467. let attributesSnippet = `@location( ${index} )`;
  44468. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  44469. attributesSnippet += ' @interpolate( flat )';
  44470. }
  44471. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  44472. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  44473. vars.push( varying );
  44474. }
  44475. }
  44476. }
  44477. const builtins = this.getBuiltins( shaderStage );
  44478. if ( builtins ) snippets.push( builtins );
  44479. const code = snippets.join( ',\n\t' );
  44480. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  44481. }
  44482. /**
  44483. * Returns the uniforms of the given shader stage as a WGSL string.
  44484. *
  44485. * @param {String} shaderStage - The shader stage.
  44486. * @return {String} The WGSL snippet that defines the uniforms.
  44487. */
  44488. getUniforms( shaderStage ) {
  44489. const uniforms = this.uniforms[ shaderStage ];
  44490. const bindingSnippets = [];
  44491. const bufferSnippets = [];
  44492. const structSnippets = [];
  44493. const uniformGroups = {};
  44494. for ( const uniform of uniforms ) {
  44495. const groupName = uniform.groupNode.name;
  44496. const uniformIndexes = this.bindingsIndexes[ groupName ];
  44497. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  44498. const texture = uniform.node.value;
  44499. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  44500. if ( this.isSampleCompare( texture ) ) {
  44501. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  44502. } else {
  44503. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  44504. }
  44505. }
  44506. let textureType;
  44507. let multisampled = '';
  44508. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44509. if ( primarySamples > 1 ) {
  44510. multisampled = '_multisampled';
  44511. }
  44512. if ( texture.isCubeTexture === true ) {
  44513. textureType = 'texture_cube<f32>';
  44514. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44515. textureType = 'texture_2d_array<f32>';
  44516. } else if ( texture.isDepthTexture === true ) {
  44517. textureType = `texture_depth${multisampled}_2d`;
  44518. } else if ( texture.isVideoTexture === true ) {
  44519. textureType = 'texture_external';
  44520. } else if ( texture.isData3DTexture === true ) {
  44521. textureType = 'texture_3d<f32>';
  44522. } else if ( uniform.node.isStorageTextureNode === true ) {
  44523. const format = getFormat( texture );
  44524. const access = this.getStorageAccess( uniform.node, shaderStage );
  44525. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  44526. } else {
  44527. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  44528. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  44529. }
  44530. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  44531. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  44532. const bufferNode = uniform.node;
  44533. const bufferType = this.getType( bufferNode.bufferType );
  44534. const bufferCount = bufferNode.bufferCount;
  44535. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  44536. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  44537. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  44538. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  44539. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  44540. } else {
  44541. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  44542. const groupName = uniform.groupNode.name;
  44543. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  44544. index: uniformIndexes.binding ++,
  44545. id: uniformIndexes.group,
  44546. snippets: []
  44547. } );
  44548. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  44549. }
  44550. }
  44551. for ( const name in uniformGroups ) {
  44552. const group = uniformGroups[ name ];
  44553. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  44554. }
  44555. let code = bindingSnippets.join( '\n' );
  44556. code += bufferSnippets.join( '\n' );
  44557. code += structSnippets.join( '\n' );
  44558. return code;
  44559. }
  44560. /**
  44561. * Controls the code build of the shader stages.
  44562. */
  44563. buildCode() {
  44564. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44565. this.sortBindingGroups();
  44566. for ( const shaderStage in shadersData ) {
  44567. const stageData = shadersData[ shaderStage ];
  44568. stageData.uniforms = this.getUniforms( shaderStage );
  44569. stageData.attributes = this.getAttributes( shaderStage );
  44570. stageData.varyings = this.getVaryings( shaderStage );
  44571. stageData.structs = this.getStructs( shaderStage );
  44572. stageData.vars = this.getVars( shaderStage );
  44573. stageData.codes = this.getCodes( shaderStage );
  44574. stageData.directives = this.getDirectives( shaderStage );
  44575. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  44576. //
  44577. let flow = '// code\n\n';
  44578. flow += this.flowCode[ shaderStage ];
  44579. const flowNodes = this.flowNodes[ shaderStage ];
  44580. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44581. const outputNode = mainNode.outputNode;
  44582. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  44583. for ( const node of flowNodes ) {
  44584. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44585. const slotName = node.name;
  44586. if ( slotName ) {
  44587. if ( flow.length > 0 ) flow += '\n';
  44588. flow += `\t// flow -> ${ slotName }\n`;
  44589. }
  44590. flow += `${ flowSlotData.code }\n\t`;
  44591. if ( node === mainNode && shaderStage !== 'compute' ) {
  44592. flow += '// result\n\n\t';
  44593. if ( shaderStage === 'vertex' ) {
  44594. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  44595. } else if ( shaderStage === 'fragment' ) {
  44596. if ( isOutputStruct ) {
  44597. stageData.returnType = outputNode.nodeType;
  44598. flow += `return ${ flowSlotData.result };`;
  44599. } else {
  44600. let structSnippet = '\t@location(0) color: vec4<f32>';
  44601. const builtins = this.getBuiltins( 'output' );
  44602. if ( builtins ) structSnippet += ',\n\t' + builtins;
  44603. stageData.returnType = 'OutputStruct';
  44604. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  44605. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  44606. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  44607. }
  44608. }
  44609. }
  44610. }
  44611. stageData.flow = flow;
  44612. }
  44613. if ( this.material !== null ) {
  44614. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  44615. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  44616. } else {
  44617. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  44618. }
  44619. }
  44620. /**
  44621. * Returns the native shader method name for a given generic name.
  44622. *
  44623. * @param {String} method - The method name to resolve.
  44624. * @param {String} [output=null] - An optional output.
  44625. * @return {String} The resolved WGSL method name.
  44626. */
  44627. getMethod( method, output = null ) {
  44628. let wgslMethod;
  44629. if ( output !== null ) {
  44630. wgslMethod = this._getWGSLMethod( method + '_' + output );
  44631. }
  44632. if ( wgslMethod === undefined ) {
  44633. wgslMethod = this._getWGSLMethod( method );
  44634. }
  44635. return wgslMethod || method;
  44636. }
  44637. /**
  44638. * Returns the WGSL type of the given node data type.
  44639. *
  44640. * @param {String} type - The node data type.
  44641. * @return {String} The WGSL type.
  44642. */
  44643. getType( type ) {
  44644. return wgslTypeLib[ type ] || type;
  44645. }
  44646. /**
  44647. * Whether the requested feature is available or not.
  44648. *
  44649. * @param {String} name - The requested feature.
  44650. * @return {Boolean} Whether the requested feature is supported or not.
  44651. */
  44652. isAvailable( name ) {
  44653. let result = supports[ name ];
  44654. if ( result === undefined ) {
  44655. if ( name === 'float32Filterable' ) {
  44656. result = this.renderer.hasFeature( 'float32-filterable' );
  44657. } else if ( name === 'clipDistance' ) {
  44658. result = this.renderer.hasFeature( 'clip-distances' );
  44659. }
  44660. supports[ name ] = result;
  44661. }
  44662. return result;
  44663. }
  44664. /**
  44665. * Returns the native shader method name for a given generic name.
  44666. *
  44667. * @private
  44668. * @param {String} method - The method name to resolve.
  44669. * @return {String} The resolved WGSL method name.
  44670. */
  44671. _getWGSLMethod( method ) {
  44672. if ( wgslPolyfill[ method ] !== undefined ) {
  44673. this._include( method );
  44674. }
  44675. return wgslMethods[ method ];
  44676. }
  44677. /**
  44678. * Includes the given method name into the current
  44679. * function node.
  44680. *
  44681. * @private
  44682. * @param {String} name - The method name to include.
  44683. * @return {CodeNode} The respective code node.
  44684. */
  44685. _include( name ) {
  44686. const codeNode = wgslPolyfill[ name ];
  44687. codeNode.build( this );
  44688. if ( this.currentFunctionNode !== null ) {
  44689. this.currentFunctionNode.includes.push( codeNode );
  44690. }
  44691. return codeNode;
  44692. }
  44693. /**
  44694. * Returns a WGSL vertex shader based on the given shader data.
  44695. *
  44696. * @private
  44697. * @param {Object} shaderData - The shader data.
  44698. * @return {String} The vertex shader.
  44699. */
  44700. _getWGSLVertexCode( shaderData ) {
  44701. return `${ this.getSignature() }
  44702. // directives
  44703. ${shaderData.directives}
  44704. // uniforms
  44705. ${shaderData.uniforms}
  44706. // varyings
  44707. ${shaderData.varyings}
  44708. var<private> varyings : VaryingsStruct;
  44709. // codes
  44710. ${shaderData.codes}
  44711. @vertex
  44712. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  44713. // vars
  44714. ${shaderData.vars}
  44715. // flow
  44716. ${shaderData.flow}
  44717. return varyings;
  44718. }
  44719. `;
  44720. }
  44721. /**
  44722. * Returns a WGSL fragment shader based on the given shader data.
  44723. *
  44724. * @private
  44725. * @param {Object} shaderData - The shader data.
  44726. * @return {String} The vertex shader.
  44727. */
  44728. _getWGSLFragmentCode( shaderData ) {
  44729. return `${ this.getSignature() }
  44730. // global
  44731. ${ diagnostics }
  44732. // uniforms
  44733. ${shaderData.uniforms}
  44734. // structs
  44735. ${shaderData.structs}
  44736. // codes
  44737. ${shaderData.codes}
  44738. @fragment
  44739. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  44740. // vars
  44741. ${shaderData.vars}
  44742. // flow
  44743. ${shaderData.flow}
  44744. }
  44745. `;
  44746. }
  44747. /**
  44748. * Returns a WGSL compute shader based on the given shader data.
  44749. *
  44750. * @private
  44751. * @param {Object} shaderData - The shader data.
  44752. * @param {String} workgroupSize - The workgroup size.
  44753. * @return {String} The vertex shader.
  44754. */
  44755. _getWGSLComputeCode( shaderData, workgroupSize ) {
  44756. return `${ this.getSignature() }
  44757. // directives
  44758. ${shaderData.directives}
  44759. // system
  44760. var<private> instanceIndex : u32;
  44761. // locals
  44762. ${shaderData.scopedArrays}
  44763. // uniforms
  44764. ${shaderData.uniforms}
  44765. // codes
  44766. ${shaderData.codes}
  44767. @compute @workgroup_size( ${workgroupSize} )
  44768. fn main( ${shaderData.attributes} ) {
  44769. // system
  44770. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  44771. // vars
  44772. ${shaderData.vars}
  44773. // flow
  44774. ${shaderData.flow}
  44775. }
  44776. `;
  44777. }
  44778. /**
  44779. * Returns a WGSL struct based on the given name and variables.
  44780. *
  44781. * @private
  44782. * @param {String} name - The struct name.
  44783. * @param {String} vars - The struct variables.
  44784. * @return {String} The WGSL snippet representing a struct.
  44785. */
  44786. _getWGSLStruct( name, vars ) {
  44787. return `
  44788. struct ${name} {
  44789. ${vars}
  44790. };`;
  44791. }
  44792. /**
  44793. * Returns a WGSL struct binding.
  44794. *
  44795. * @private
  44796. * @param {String} name - The struct name.
  44797. * @param {String} vars - The struct variables.
  44798. * @param {String} access - The access.
  44799. * @param {Number} [binding=0] - The binding index.
  44800. * @param {Number} [group=0] - The group index.
  44801. * @return {String} The WGSL snippet representing a struct binding.
  44802. */
  44803. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  44804. const structName = name + 'Struct';
  44805. const structSnippet = this._getWGSLStruct( structName, vars );
  44806. return `${structSnippet}
  44807. @binding( ${binding} ) @group( ${group} )
  44808. var<${access}> ${name} : ${structName};`;
  44809. }
  44810. }
  44811. /**
  44812. * A WebGPU backend utility module with common helpers.
  44813. *
  44814. * @private
  44815. */
  44816. class WebGPUUtils {
  44817. /**
  44818. * Constructs a new utility object.
  44819. *
  44820. * @param {WebGPUBackend} backend - The WebGPU backend.
  44821. */
  44822. constructor( backend ) {
  44823. /**
  44824. * A reference to the WebGPU backend.
  44825. *
  44826. * @type {WebGPUBackend}
  44827. */
  44828. this.backend = backend;
  44829. }
  44830. /**
  44831. * Returns the depth/stencil GPU format for the given render context.
  44832. *
  44833. * @param {RenderContext} renderContext - The render context.
  44834. * @return {String} The depth/stencil GPU texture format.
  44835. */
  44836. getCurrentDepthStencilFormat( renderContext ) {
  44837. let format;
  44838. if ( renderContext.depthTexture !== null ) {
  44839. format = this.getTextureFormatGPU( renderContext.depthTexture );
  44840. } else if ( renderContext.depth && renderContext.stencil ) {
  44841. format = GPUTextureFormat.Depth24PlusStencil8;
  44842. } else if ( renderContext.depth ) {
  44843. format = GPUTextureFormat.Depth24Plus;
  44844. }
  44845. return format;
  44846. }
  44847. /**
  44848. * Returns the GPU format for the given texture.
  44849. *
  44850. * @param {Texture} texture - The texture.
  44851. * @return {String} The GPU texture format.
  44852. */
  44853. getTextureFormatGPU( texture ) {
  44854. return this.backend.get( texture ).format;
  44855. }
  44856. /**
  44857. * Returns an object that defines the multi-sampling state of the given texture.
  44858. *
  44859. * @param {Texture} texture - The texture.
  44860. * @return {Object} The multi-sampling state.
  44861. */
  44862. getTextureSampleData( texture ) {
  44863. let samples;
  44864. if ( texture.isFramebufferTexture ) {
  44865. samples = 1;
  44866. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  44867. const renderer = this.backend.renderer;
  44868. const renderTarget = renderer.getRenderTarget();
  44869. samples = renderTarget ? renderTarget.samples : renderer.samples;
  44870. } else if ( texture.renderTarget ) {
  44871. samples = texture.renderTarget.samples;
  44872. }
  44873. samples = samples || 1;
  44874. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  44875. const primarySamples = isMSAA ? 1 : samples;
  44876. return { samples, primarySamples, isMSAA };
  44877. }
  44878. /**
  44879. * Returns the default color attachment's GPU format of the current render context.
  44880. *
  44881. * @param {RenderContext} renderContext - The render context.
  44882. * @return {String} The GPU texture format of the default color attachment.
  44883. */
  44884. getCurrentColorFormat( renderContext ) {
  44885. let format;
  44886. if ( renderContext.textures !== null ) {
  44887. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  44888. } else {
  44889. format = this.getPreferredCanvasFormat(); // default context format
  44890. }
  44891. return format;
  44892. }
  44893. /**
  44894. * Returns the output color space of the current render context.
  44895. *
  44896. * @param {RenderContext} renderContext - The render context.
  44897. * @return {String} The output color space.
  44898. */
  44899. getCurrentColorSpace( renderContext ) {
  44900. if ( renderContext.textures !== null ) {
  44901. return renderContext.textures[ 0 ].colorSpace;
  44902. }
  44903. return this.backend.renderer.outputColorSpace;
  44904. }
  44905. /**
  44906. * Returns GPU primitive topology for the given object and material.
  44907. *
  44908. * @param {Object3D} object - The 3D object.
  44909. * @param {Material} material - The material.
  44910. * @return {String} The GPU primitive topology.
  44911. */
  44912. getPrimitiveTopology( object, material ) {
  44913. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  44914. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  44915. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  44916. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  44917. }
  44918. /**
  44919. * Returns a modified sample count from the given sample count value.
  44920. *
  44921. * That is required since WebGPU does not support arbitrary sample counts.
  44922. *
  44923. * @param {Number} sampleCount - The input sample count.
  44924. * @return {Number} The (potentially updated) output sample count.
  44925. */
  44926. getSampleCount( sampleCount ) {
  44927. let count = 1;
  44928. if ( sampleCount > 1 ) {
  44929. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  44930. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  44931. if ( count === 2 ) {
  44932. count = 4;
  44933. }
  44934. }
  44935. return count;
  44936. }
  44937. /**
  44938. * Returns the sample count of the given render context.
  44939. *
  44940. * @param {RenderContext} renderContext - The render context.
  44941. * @return {Number} The sample count.
  44942. */
  44943. getSampleCountRenderContext( renderContext ) {
  44944. if ( renderContext.textures !== null ) {
  44945. return this.getSampleCount( renderContext.sampleCount );
  44946. }
  44947. return this.getSampleCount( this.backend.renderer.samples );
  44948. }
  44949. /**
  44950. * Returns the preferred canvas format.
  44951. *
  44952. * There is a separate method for this so it's possible to
  44953. * honor edge cases for specific devices.
  44954. *
  44955. * @return {String} The GPU texture format of the canvas.
  44956. */
  44957. getPreferredCanvasFormat() {
  44958. const outputType = this.backend.parameters.outputType;
  44959. if ( outputType === undefined ) {
  44960. return navigator.gpu.getPreferredCanvasFormat();
  44961. } else if ( outputType === UnsignedByteType ) {
  44962. return GPUTextureFormat.BGRA8Unorm;
  44963. } else if ( outputType === HalfFloatType ) {
  44964. return GPUTextureFormat.RGBA16Float;
  44965. } else {
  44966. throw new Error( 'Unsupported outputType' );
  44967. }
  44968. }
  44969. }
  44970. const typedArraysToVertexFormatPrefix = new Map( [
  44971. [ Int8Array, [ 'sint8', 'snorm8' ]],
  44972. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  44973. [ Int16Array, [ 'sint16', 'snorm16' ]],
  44974. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  44975. [ Int32Array, [ 'sint32', 'snorm32' ]],
  44976. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  44977. [ Float32Array, [ 'float32', ]],
  44978. ] );
  44979. const typedAttributeToVertexFormatPrefix = new Map( [
  44980. [ Float16BufferAttribute, [ 'float16', ]],
  44981. ] );
  44982. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  44983. [ Int32Array, 'sint32' ],
  44984. [ Int16Array, 'sint32' ], // patch for INT16
  44985. [ Uint32Array, 'uint32' ],
  44986. [ Uint16Array, 'uint32' ], // patch for UINT16
  44987. [ Float32Array, 'float32' ]
  44988. ] );
  44989. /**
  44990. * A WebGPU backend utility module for managing shader attributes.
  44991. *
  44992. * @private
  44993. */
  44994. class WebGPUAttributeUtils {
  44995. /**
  44996. * Constructs a new utility object.
  44997. *
  44998. * @param {WebGPUBackend} backend - The WebGPU backend.
  44999. */
  45000. constructor( backend ) {
  45001. /**
  45002. * A reference to the WebGPU backend.
  45003. *
  45004. * @type {WebGPUBackend}
  45005. */
  45006. this.backend = backend;
  45007. }
  45008. /**
  45009. * Creates the GPU buffer for the given buffer attribute.
  45010. *
  45011. * @param {BufferAttribute} attribute - The buffer attribute.
  45012. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  45013. */
  45014. createAttribute( attribute, usage ) {
  45015. const bufferAttribute = this._getBufferAttribute( attribute );
  45016. const backend = this.backend;
  45017. const bufferData = backend.get( bufferAttribute );
  45018. let buffer = bufferData.buffer;
  45019. if ( buffer === undefined ) {
  45020. const device = backend.device;
  45021. let array = bufferAttribute.array;
  45022. // patch for INT16 and UINT16
  45023. if ( attribute.normalized === false ) {
  45024. if ( array.constructor === Int16Array ) {
  45025. array = new Int32Array( array );
  45026. } else if ( array.constructor === Uint16Array ) {
  45027. array = new Uint32Array( array );
  45028. if ( usage & GPUBufferUsage.INDEX ) {
  45029. for ( let i = 0; i < array.length; i ++ ) {
  45030. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  45031. }
  45032. }
  45033. }
  45034. }
  45035. bufferAttribute.array = array;
  45036. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  45037. array = new array.constructor( bufferAttribute.count * 4 );
  45038. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  45039. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  45040. }
  45041. // Update BufferAttribute
  45042. bufferAttribute.itemSize = 4;
  45043. bufferAttribute.array = array;
  45044. }
  45045. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  45046. buffer = device.createBuffer( {
  45047. label: bufferAttribute.name,
  45048. size: size,
  45049. usage: usage,
  45050. mappedAtCreation: true
  45051. } );
  45052. new array.constructor( buffer.getMappedRange() ).set( array );
  45053. buffer.unmap();
  45054. bufferData.buffer = buffer;
  45055. }
  45056. }
  45057. /**
  45058. * Updates the GPU buffer of the given buffer attribute.
  45059. *
  45060. * @param {BufferAttribute} attribute - The buffer attribute.
  45061. */
  45062. updateAttribute( attribute ) {
  45063. const bufferAttribute = this._getBufferAttribute( attribute );
  45064. const backend = this.backend;
  45065. const device = backend.device;
  45066. const buffer = backend.get( bufferAttribute ).buffer;
  45067. const array = bufferAttribute.array;
  45068. const isTypedArray = this._isTypedArray( array );
  45069. const updateRanges = bufferAttribute.updateRanges;
  45070. if ( updateRanges.length === 0 ) {
  45071. // Not using update ranges
  45072. device.queue.writeBuffer(
  45073. buffer,
  45074. 0,
  45075. array,
  45076. 0
  45077. );
  45078. } else {
  45079. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  45080. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45081. const range = updateRanges[ i ];
  45082. const dataOffset = range.start * byteOffsetFactor;
  45083. const size = range.count * byteOffsetFactor;
  45084. device.queue.writeBuffer(
  45085. buffer,
  45086. 0,
  45087. array,
  45088. dataOffset,
  45089. size
  45090. );
  45091. }
  45092. bufferAttribute.clearUpdateRanges();
  45093. }
  45094. }
  45095. /**
  45096. * This method creates the vertex buffer layout data which are
  45097. * require when creating a render pipeline for the given render object.
  45098. *
  45099. * @param {RenderObject} renderObject - The render object.
  45100. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  45101. */
  45102. createShaderVertexBuffers( renderObject ) {
  45103. const attributes = renderObject.getAttributes();
  45104. const vertexBuffers = new Map();
  45105. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  45106. const geometryAttribute = attributes[ slot ];
  45107. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  45108. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  45109. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  45110. if ( vertexBufferLayout === undefined ) {
  45111. let arrayStride, stepMode;
  45112. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  45113. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  45114. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45115. } else {
  45116. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  45117. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45118. }
  45119. // patch for INT16 and UINT16
  45120. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  45121. arrayStride = 4;
  45122. }
  45123. vertexBufferLayout = {
  45124. arrayStride,
  45125. attributes: [],
  45126. stepMode
  45127. };
  45128. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  45129. }
  45130. const format = this._getVertexFormat( geometryAttribute );
  45131. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  45132. vertexBufferLayout.attributes.push( {
  45133. shaderLocation: slot,
  45134. offset,
  45135. format
  45136. } );
  45137. }
  45138. return Array.from( vertexBuffers.values() );
  45139. }
  45140. /**
  45141. * Destroys the GPU buffer of the given buffer attribute.
  45142. *
  45143. * @param {BufferAttribute} attribute - The buffer attribute.
  45144. */
  45145. destroyAttribute( attribute ) {
  45146. const backend = this.backend;
  45147. const data = backend.get( this._getBufferAttribute( attribute ) );
  45148. data.buffer.destroy();
  45149. backend.delete( attribute );
  45150. }
  45151. /**
  45152. * This method performs a readback operation by moving buffer data from
  45153. * a storage buffer attribute from the GPU to the CPU.
  45154. *
  45155. * @async
  45156. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45157. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45158. */
  45159. async getArrayBufferAsync( attribute ) {
  45160. const backend = this.backend;
  45161. const device = backend.device;
  45162. const data = backend.get( this._getBufferAttribute( attribute ) );
  45163. const bufferGPU = data.buffer;
  45164. const size = bufferGPU.size;
  45165. const readBufferGPU = device.createBuffer( {
  45166. label: `${ attribute.name }_readback`,
  45167. size,
  45168. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45169. } );
  45170. const cmdEncoder = device.createCommandEncoder( {
  45171. label: `readback_encoder_${ attribute.name }`
  45172. } );
  45173. cmdEncoder.copyBufferToBuffer(
  45174. bufferGPU,
  45175. 0,
  45176. readBufferGPU,
  45177. 0,
  45178. size
  45179. );
  45180. const gpuCommands = cmdEncoder.finish();
  45181. device.queue.submit( [ gpuCommands ] );
  45182. await readBufferGPU.mapAsync( GPUMapMode.READ );
  45183. const arrayBuffer = readBufferGPU.getMappedRange();
  45184. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  45185. readBufferGPU.unmap();
  45186. return dstBuffer.buffer;
  45187. }
  45188. /**
  45189. * Returns the vertex format of the given buffer attribute.
  45190. *
  45191. * @private
  45192. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  45193. * @return {String} The vertex format (e.g. 'float32x3').
  45194. */
  45195. _getVertexFormat( geometryAttribute ) {
  45196. const { itemSize, normalized } = geometryAttribute;
  45197. const ArrayType = geometryAttribute.array.constructor;
  45198. const AttributeType = geometryAttribute.constructor;
  45199. let format;
  45200. if ( itemSize === 1 ) {
  45201. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  45202. } else {
  45203. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  45204. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  45205. if ( prefix ) {
  45206. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  45207. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  45208. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  45209. if ( paddedItemSize % 1 ) {
  45210. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  45211. }
  45212. format = `${prefix}x${paddedItemSize}`;
  45213. }
  45214. }
  45215. if ( ! format ) {
  45216. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  45217. }
  45218. return format;
  45219. }
  45220. /**
  45221. * Returns `true` if the given array is a typed array.
  45222. *
  45223. * @private
  45224. * @param {Any} array - The array.
  45225. * @return {Boolean} Whether the given array is a typed array or not.
  45226. */
  45227. _isTypedArray( array ) {
  45228. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  45229. }
  45230. /**
  45231. * Utility method for handling interleaved buffer attributes correctly.
  45232. * To process them, their `InterleavedBuffer` is returned.
  45233. *
  45234. * @private
  45235. * @param {BufferAttribute} attribute - The attribute.
  45236. * @return {BufferAttribute|InterleavedBuffer}
  45237. */
  45238. _getBufferAttribute( attribute ) {
  45239. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  45240. return attribute;
  45241. }
  45242. }
  45243. /**
  45244. * A WebGPU backend utility module for managing bindings.
  45245. *
  45246. * When reading the documentation it's helpful to keep in mind that
  45247. * all class definitions starting with 'GPU*' are modules from the
  45248. * WebGPU API. So for example `BindGroup` is a class from the engine
  45249. * whereas `GPUBindGroup` is a class from WebGPU.
  45250. *
  45251. * @private
  45252. */
  45253. class WebGPUBindingUtils {
  45254. /**
  45255. * Constructs a new utility object.
  45256. *
  45257. * @param {WebGPUBackend} backend - The WebGPU backend.
  45258. */
  45259. constructor( backend ) {
  45260. /**
  45261. * A reference to the WebGPU backend.
  45262. *
  45263. * @type {WebGPUBackend}
  45264. */
  45265. this.backend = backend;
  45266. /**
  45267. * A cache for managing bind group layouts.
  45268. *
  45269. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  45270. */
  45271. this.bindGroupLayoutCache = new WeakMap();
  45272. }
  45273. /**
  45274. * Creates a GPU bind group layout for the given bind group.
  45275. *
  45276. * @param {BindGroup} bindGroup - The bind group.
  45277. * @return {GPUBindGroupLayout} The GPU bind group layout.
  45278. */
  45279. createBindingsLayout( bindGroup ) {
  45280. const backend = this.backend;
  45281. const device = backend.device;
  45282. const entries = [];
  45283. let index = 0;
  45284. for ( const binding of bindGroup.bindings ) {
  45285. const bindingGPU = {
  45286. binding: index ++,
  45287. visibility: binding.visibility
  45288. };
  45289. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45290. const buffer = {}; // GPUBufferBindingLayout
  45291. if ( binding.isStorageBuffer ) {
  45292. if ( binding.visibility & 4 ) {
  45293. // compute
  45294. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  45295. buffer.type = GPUBufferBindingType.Storage;
  45296. } else {
  45297. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45298. }
  45299. } else {
  45300. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45301. }
  45302. }
  45303. bindingGPU.buffer = buffer;
  45304. } else if ( binding.isSampler ) {
  45305. const sampler = {}; // GPUSamplerBindingLayout
  45306. if ( binding.texture.isDepthTexture ) {
  45307. if ( binding.texture.compareFunction !== null ) {
  45308. sampler.type = 'comparison';
  45309. }
  45310. }
  45311. bindingGPU.sampler = sampler;
  45312. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45313. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45314. } else if ( binding.isSampledTexture && binding.store ) {
  45315. const storageTexture = {}; // GPUStorageTextureBindingLayout
  45316. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  45317. const access = binding.access;
  45318. if ( access === NodeAccess.READ_WRITE ) {
  45319. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  45320. } else if ( access === NodeAccess.WRITE_ONLY ) {
  45321. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  45322. } else {
  45323. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  45324. }
  45325. bindingGPU.storageTexture = storageTexture;
  45326. } else if ( binding.isSampledTexture ) {
  45327. const texture = {}; // GPUTextureBindingLayout
  45328. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  45329. if ( primarySamples > 1 ) {
  45330. texture.multisampled = true;
  45331. if ( ! binding.texture.isDepthTexture ) {
  45332. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45333. }
  45334. }
  45335. if ( binding.texture.isDepthTexture ) {
  45336. texture.sampleType = GPUTextureSampleType.Depth;
  45337. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  45338. const type = binding.texture.type;
  45339. if ( type === IntType ) {
  45340. texture.sampleType = GPUTextureSampleType.SInt;
  45341. } else if ( type === UnsignedIntType ) {
  45342. texture.sampleType = GPUTextureSampleType.UInt;
  45343. } else if ( type === FloatType ) {
  45344. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  45345. texture.sampleType = GPUTextureSampleType.Float;
  45346. } else {
  45347. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45348. }
  45349. }
  45350. }
  45351. if ( binding.isSampledCubeTexture ) {
  45352. texture.viewDimension = GPUTextureViewDimension.Cube;
  45353. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45354. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  45355. } else if ( binding.isSampledTexture3D ) {
  45356. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  45357. }
  45358. bindingGPU.texture = texture;
  45359. } else {
  45360. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  45361. }
  45362. entries.push( bindingGPU );
  45363. }
  45364. return device.createBindGroupLayout( { entries } );
  45365. }
  45366. /**
  45367. * Creates bindings from the given bind group definition.
  45368. *
  45369. * @param {BindGroup} bindGroup - The bind group.
  45370. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45371. * @param {Number} cacheIndex - The cache index.
  45372. * @param {Number} version - The version.
  45373. */
  45374. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  45375. const { backend, bindGroupLayoutCache } = this;
  45376. const bindingsData = backend.get( bindGroup );
  45377. // setup (static) binding layout and (dynamic) binding group
  45378. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  45379. if ( bindLayoutGPU === undefined ) {
  45380. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  45381. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  45382. }
  45383. let bindGroupGPU;
  45384. if ( cacheIndex > 0 ) {
  45385. if ( bindingsData.groups === undefined ) {
  45386. bindingsData.groups = [];
  45387. bindingsData.versions = [];
  45388. }
  45389. if ( bindingsData.versions[ cacheIndex ] === version ) {
  45390. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  45391. }
  45392. }
  45393. if ( bindGroupGPU === undefined ) {
  45394. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  45395. if ( cacheIndex > 0 ) {
  45396. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  45397. bindingsData.versions[ cacheIndex ] = version;
  45398. }
  45399. }
  45400. bindingsData.group = bindGroupGPU;
  45401. bindingsData.layout = bindLayoutGPU;
  45402. }
  45403. /**
  45404. * Updates a buffer binding.
  45405. *
  45406. * @param {Buffer} binding - The buffer binding to update.
  45407. */
  45408. updateBinding( binding ) {
  45409. const backend = this.backend;
  45410. const device = backend.device;
  45411. const buffer = binding.buffer;
  45412. const bufferGPU = backend.get( binding ).buffer;
  45413. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  45414. }
  45415. /**
  45416. * Creates a GPU bind group for the camera index.
  45417. *
  45418. * @param {Uint32Array} data - The index data.
  45419. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  45420. * @return {GPUBindGroup} The GPU bind group.
  45421. */
  45422. createBindGroupIndex( data, layout ) {
  45423. const backend = this.backend;
  45424. const device = backend.device;
  45425. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45426. const index = data[ 0 ];
  45427. const buffer = device.createBuffer( {
  45428. label: 'bindingCameraIndex_' + index,
  45429. size: 16, // uint(4) * 4
  45430. usage: usage
  45431. } );
  45432. device.queue.writeBuffer( buffer, 0, data, 0 );
  45433. const entries = [ { binding: 0, resource: { buffer } } ];
  45434. return device.createBindGroup( {
  45435. label: 'bindGroupCameraIndex_' + index,
  45436. layout,
  45437. entries
  45438. } );
  45439. }
  45440. /**
  45441. * Creates a GPU bind group for the given bind group and GPU layout.
  45442. *
  45443. * @param {BindGroup} bindGroup - The bind group.
  45444. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  45445. * @return {GPUBindGroup} The GPU bind group.
  45446. */
  45447. createBindGroup( bindGroup, layoutGPU ) {
  45448. const backend = this.backend;
  45449. const device = backend.device;
  45450. let bindingPoint = 0;
  45451. const entriesGPU = [];
  45452. for ( const binding of bindGroup.bindings ) {
  45453. if ( binding.isUniformBuffer ) {
  45454. const bindingData = backend.get( binding );
  45455. if ( bindingData.buffer === undefined ) {
  45456. const byteLength = binding.byteLength;
  45457. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45458. const bufferGPU = device.createBuffer( {
  45459. label: 'bindingBuffer_' + binding.name,
  45460. size: byteLength,
  45461. usage: usage
  45462. } );
  45463. bindingData.buffer = bufferGPU;
  45464. }
  45465. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45466. } else if ( binding.isStorageBuffer ) {
  45467. const bindingData = backend.get( binding );
  45468. if ( bindingData.buffer === undefined ) {
  45469. const attribute = binding.attribute;
  45470. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  45471. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  45472. bindingData.buffer = backend.get( attribute ).buffer;
  45473. }
  45474. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45475. } else if ( binding.isSampler ) {
  45476. const textureGPU = backend.get( binding.texture );
  45477. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  45478. } else if ( binding.isSampledTexture ) {
  45479. const textureData = backend.get( binding.texture );
  45480. let resourceGPU;
  45481. if ( textureData.externalTexture !== undefined ) {
  45482. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  45483. } else {
  45484. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  45485. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  45486. resourceGPU = textureData[ propertyName ];
  45487. if ( resourceGPU === undefined ) {
  45488. const aspectGPU = GPUTextureAspect.All;
  45489. let dimensionViewGPU;
  45490. if ( binding.isSampledCubeTexture ) {
  45491. dimensionViewGPU = GPUTextureViewDimension.Cube;
  45492. } else if ( binding.isSampledTexture3D ) {
  45493. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  45494. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45495. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  45496. } else {
  45497. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  45498. }
  45499. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  45500. }
  45501. }
  45502. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  45503. }
  45504. bindingPoint ++;
  45505. }
  45506. return device.createBindGroup( {
  45507. label: 'bindGroup_' + bindGroup.name,
  45508. layout: layoutGPU,
  45509. entries: entriesGPU
  45510. } );
  45511. }
  45512. }
  45513. /**
  45514. * A WebGPU backend utility module for managing pipelines.
  45515. *
  45516. * @private
  45517. */
  45518. class WebGPUPipelineUtils {
  45519. /**
  45520. * Constructs a new utility object.
  45521. *
  45522. * @param {WebGPUBackend} backend - The WebGPU backend.
  45523. */
  45524. constructor( backend ) {
  45525. /**
  45526. * A reference to the WebGPU backend.
  45527. *
  45528. * @type {WebGPUBackend}
  45529. */
  45530. this.backend = backend;
  45531. }
  45532. /**
  45533. * Returns the sample count derived from the given render context.
  45534. *
  45535. * @private
  45536. * @param {RenderContext} renderContext - The render context.
  45537. * @return {Number} The sample count.
  45538. */
  45539. _getSampleCount( renderContext ) {
  45540. return this.backend.utils.getSampleCountRenderContext( renderContext );
  45541. }
  45542. /**
  45543. * Creates a render pipeline for the given render object.
  45544. *
  45545. * @param {RenderObject} renderObject - The render object.
  45546. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45547. */
  45548. createRenderPipeline( renderObject, promises ) {
  45549. const { object, material, geometry, pipeline } = renderObject;
  45550. const { vertexProgram, fragmentProgram } = pipeline;
  45551. const backend = this.backend;
  45552. const device = backend.device;
  45553. const utils = backend.utils;
  45554. const pipelineData = backend.get( pipeline );
  45555. // bind group layouts
  45556. const bindGroupLayouts = [];
  45557. for ( const bindGroup of renderObject.getBindings() ) {
  45558. const bindingsData = backend.get( bindGroup );
  45559. bindGroupLayouts.push( bindingsData.layout );
  45560. }
  45561. // vertex buffers
  45562. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  45563. // blending
  45564. let blending;
  45565. if ( material.transparent === true && material.blending !== NoBlending ) {
  45566. blending = this._getBlending( material );
  45567. }
  45568. // stencil
  45569. let stencilFront = {};
  45570. if ( material.stencilWrite === true ) {
  45571. stencilFront = {
  45572. compare: this._getStencilCompare( material ),
  45573. failOp: this._getStencilOperation( material.stencilFail ),
  45574. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  45575. passOp: this._getStencilOperation( material.stencilZPass )
  45576. };
  45577. }
  45578. const colorWriteMask = this._getColorWriteMask( material );
  45579. const targets = [];
  45580. if ( renderObject.context.textures !== null ) {
  45581. const textures = renderObject.context.textures;
  45582. for ( let i = 0; i < textures.length; i ++ ) {
  45583. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  45584. targets.push( {
  45585. format: colorFormat,
  45586. blend: blending,
  45587. writeMask: colorWriteMask
  45588. } );
  45589. }
  45590. } else {
  45591. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45592. targets.push( {
  45593. format: colorFormat,
  45594. blend: blending,
  45595. writeMask: colorWriteMask
  45596. } );
  45597. }
  45598. const vertexModule = backend.get( vertexProgram ).module;
  45599. const fragmentModule = backend.get( fragmentProgram ).module;
  45600. const primitiveState = this._getPrimitiveState( object, geometry, material );
  45601. const depthCompare = this._getDepthCompare( material );
  45602. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45603. const sampleCount = this._getSampleCount( renderObject.context );
  45604. const pipelineDescriptor = {
  45605. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  45606. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  45607. fragment: Object.assign( {}, fragmentModule, { targets } ),
  45608. primitive: primitiveState,
  45609. multisample: {
  45610. count: sampleCount,
  45611. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  45612. },
  45613. layout: device.createPipelineLayout( {
  45614. bindGroupLayouts
  45615. } )
  45616. };
  45617. const depthStencil = {};
  45618. const renderDepth = renderObject.context.depth;
  45619. const renderStencil = renderObject.context.stencil;
  45620. if ( renderDepth === true || renderStencil === true ) {
  45621. if ( renderDepth === true ) {
  45622. depthStencil.format = depthStencilFormat;
  45623. depthStencil.depthWriteEnabled = material.depthWrite;
  45624. depthStencil.depthCompare = depthCompare;
  45625. }
  45626. if ( renderStencil === true ) {
  45627. depthStencil.stencilFront = stencilFront;
  45628. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  45629. depthStencil.stencilReadMask = material.stencilFuncMask;
  45630. depthStencil.stencilWriteMask = material.stencilWriteMask;
  45631. }
  45632. pipelineDescriptor.depthStencil = depthStencil;
  45633. }
  45634. if ( promises === null ) {
  45635. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  45636. } else {
  45637. const p = new Promise( ( resolve /*, reject*/ ) => {
  45638. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  45639. pipelineData.pipeline = pipeline;
  45640. resolve();
  45641. } );
  45642. } );
  45643. promises.push( p );
  45644. }
  45645. }
  45646. /**
  45647. * Creates GPU render bundle encoder for the given render context.
  45648. *
  45649. * @param {RenderContext} renderContext - The render context.
  45650. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  45651. */
  45652. createBundleEncoder( renderContext ) {
  45653. const backend = this.backend;
  45654. const { utils, device } = backend;
  45655. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  45656. const colorFormat = utils.getCurrentColorFormat( renderContext );
  45657. const sampleCount = this._getSampleCount( renderContext );
  45658. const descriptor = {
  45659. label: 'renderBundleEncoder',
  45660. colorFormats: [ colorFormat ],
  45661. depthStencilFormat,
  45662. sampleCount
  45663. };
  45664. return device.createRenderBundleEncoder( descriptor );
  45665. }
  45666. /**
  45667. * Creates a compute pipeline for the given compute node.
  45668. *
  45669. * @param {ComputePipeline} pipeline - The compute pipeline.
  45670. * @param {Array<BindGroup>} bindings - The bindings.
  45671. */
  45672. createComputePipeline( pipeline, bindings ) {
  45673. const backend = this.backend;
  45674. const device = backend.device;
  45675. const computeProgram = backend.get( pipeline.computeProgram ).module;
  45676. const pipelineGPU = backend.get( pipeline );
  45677. // bind group layouts
  45678. const bindGroupLayouts = [];
  45679. for ( const bindingsGroup of bindings ) {
  45680. const bindingsData = backend.get( bindingsGroup );
  45681. bindGroupLayouts.push( bindingsData.layout );
  45682. }
  45683. pipelineGPU.pipeline = device.createComputePipeline( {
  45684. compute: computeProgram,
  45685. layout: device.createPipelineLayout( {
  45686. bindGroupLayouts
  45687. } )
  45688. } );
  45689. }
  45690. /**
  45691. * Returns the blending state as a descriptor object required
  45692. * for the pipeline creation.
  45693. *
  45694. * @private
  45695. * @param {Material} material - The material.
  45696. * @return {Object} The blending state.
  45697. */
  45698. _getBlending( material ) {
  45699. let color, alpha;
  45700. const blending = material.blending;
  45701. const blendSrc = material.blendSrc;
  45702. const blendDst = material.blendDst;
  45703. const blendEquation = material.blendEquation;
  45704. if ( blending === CustomBlending ) {
  45705. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  45706. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  45707. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  45708. color = {
  45709. srcFactor: this._getBlendFactor( blendSrc ),
  45710. dstFactor: this._getBlendFactor( blendDst ),
  45711. operation: this._getBlendOperation( blendEquation )
  45712. };
  45713. alpha = {
  45714. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  45715. dstFactor: this._getBlendFactor( blendDstAlpha ),
  45716. operation: this._getBlendOperation( blendEquationAlpha )
  45717. };
  45718. } else {
  45719. const premultipliedAlpha = material.premultipliedAlpha;
  45720. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  45721. color = {
  45722. srcFactor: srcRGB,
  45723. dstFactor: dstRGB,
  45724. operation: GPUBlendOperation.Add
  45725. };
  45726. alpha = {
  45727. srcFactor: srcAlpha,
  45728. dstFactor: dstAlpha,
  45729. operation: GPUBlendOperation.Add
  45730. };
  45731. };
  45732. if ( premultipliedAlpha ) {
  45733. switch ( blending ) {
  45734. case NormalBlending:
  45735. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45736. break;
  45737. case AdditiveBlending:
  45738. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  45739. break;
  45740. case SubtractiveBlending:
  45741. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45742. break;
  45743. case MultiplyBlending:
  45744. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  45745. break;
  45746. }
  45747. } else {
  45748. switch ( blending ) {
  45749. case NormalBlending:
  45750. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45751. break;
  45752. case AdditiveBlending:
  45753. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  45754. break;
  45755. case SubtractiveBlending:
  45756. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45757. break;
  45758. case MultiplyBlending:
  45759. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  45760. break;
  45761. }
  45762. }
  45763. }
  45764. if ( color !== undefined && alpha !== undefined ) {
  45765. return { color, alpha };
  45766. } else {
  45767. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  45768. }
  45769. }
  45770. /**
  45771. * Returns the GPU blend factor which is required for the pipeline creation.
  45772. *
  45773. * @private
  45774. * @param {Number} blend - The blend factor as a three.js constant.
  45775. * @return {String} The GPU blend factor.
  45776. */
  45777. _getBlendFactor( blend ) {
  45778. let blendFactor;
  45779. switch ( blend ) {
  45780. case ZeroFactor:
  45781. blendFactor = GPUBlendFactor.Zero;
  45782. break;
  45783. case OneFactor:
  45784. blendFactor = GPUBlendFactor.One;
  45785. break;
  45786. case SrcColorFactor:
  45787. blendFactor = GPUBlendFactor.Src;
  45788. break;
  45789. case OneMinusSrcColorFactor:
  45790. blendFactor = GPUBlendFactor.OneMinusSrc;
  45791. break;
  45792. case SrcAlphaFactor:
  45793. blendFactor = GPUBlendFactor.SrcAlpha;
  45794. break;
  45795. case OneMinusSrcAlphaFactor:
  45796. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  45797. break;
  45798. case DstColorFactor:
  45799. blendFactor = GPUBlendFactor.Dst;
  45800. break;
  45801. case OneMinusDstColorFactor:
  45802. blendFactor = GPUBlendFactor.OneMinusDstColor;
  45803. break;
  45804. case DstAlphaFactor:
  45805. blendFactor = GPUBlendFactor.DstAlpha;
  45806. break;
  45807. case OneMinusDstAlphaFactor:
  45808. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  45809. break;
  45810. case SrcAlphaSaturateFactor:
  45811. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  45812. break;
  45813. case BlendColorFactor:
  45814. blendFactor = GPUBlendFactor.Constant;
  45815. break;
  45816. case OneMinusBlendColorFactor:
  45817. blendFactor = GPUBlendFactor.OneMinusConstant;
  45818. break;
  45819. default:
  45820. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  45821. }
  45822. return blendFactor;
  45823. }
  45824. /**
  45825. * Returns the GPU stencil compare function which is required for the pipeline creation.
  45826. *
  45827. * @private
  45828. * @param {Material} material - The material.
  45829. * @return {String} The GPU stencil compare function.
  45830. */
  45831. _getStencilCompare( material ) {
  45832. let stencilCompare;
  45833. const stencilFunc = material.stencilFunc;
  45834. switch ( stencilFunc ) {
  45835. case NeverStencilFunc:
  45836. stencilCompare = GPUCompareFunction.Never;
  45837. break;
  45838. case AlwaysStencilFunc:
  45839. stencilCompare = GPUCompareFunction.Always;
  45840. break;
  45841. case LessStencilFunc:
  45842. stencilCompare = GPUCompareFunction.Less;
  45843. break;
  45844. case LessEqualStencilFunc:
  45845. stencilCompare = GPUCompareFunction.LessEqual;
  45846. break;
  45847. case EqualStencilFunc:
  45848. stencilCompare = GPUCompareFunction.Equal;
  45849. break;
  45850. case GreaterEqualStencilFunc:
  45851. stencilCompare = GPUCompareFunction.GreaterEqual;
  45852. break;
  45853. case GreaterStencilFunc:
  45854. stencilCompare = GPUCompareFunction.Greater;
  45855. break;
  45856. case NotEqualStencilFunc:
  45857. stencilCompare = GPUCompareFunction.NotEqual;
  45858. break;
  45859. default:
  45860. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  45861. }
  45862. return stencilCompare;
  45863. }
  45864. /**
  45865. * Returns the GPU stencil operation which is required for the pipeline creation.
  45866. *
  45867. * @private
  45868. * @param {Number} op - A three.js constant defining the stencil operation.
  45869. * @return {String} The GPU stencil operation.
  45870. */
  45871. _getStencilOperation( op ) {
  45872. let stencilOperation;
  45873. switch ( op ) {
  45874. case KeepStencilOp:
  45875. stencilOperation = GPUStencilOperation.Keep;
  45876. break;
  45877. case ZeroStencilOp:
  45878. stencilOperation = GPUStencilOperation.Zero;
  45879. break;
  45880. case ReplaceStencilOp:
  45881. stencilOperation = GPUStencilOperation.Replace;
  45882. break;
  45883. case InvertStencilOp:
  45884. stencilOperation = GPUStencilOperation.Invert;
  45885. break;
  45886. case IncrementStencilOp:
  45887. stencilOperation = GPUStencilOperation.IncrementClamp;
  45888. break;
  45889. case DecrementStencilOp:
  45890. stencilOperation = GPUStencilOperation.DecrementClamp;
  45891. break;
  45892. case IncrementWrapStencilOp:
  45893. stencilOperation = GPUStencilOperation.IncrementWrap;
  45894. break;
  45895. case DecrementWrapStencilOp:
  45896. stencilOperation = GPUStencilOperation.DecrementWrap;
  45897. break;
  45898. default:
  45899. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  45900. }
  45901. return stencilOperation;
  45902. }
  45903. /**
  45904. * Returns the GPU blend operation which is required for the pipeline creation.
  45905. *
  45906. * @private
  45907. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  45908. * @return {String} The GPU blend operation.
  45909. */
  45910. _getBlendOperation( blendEquation ) {
  45911. let blendOperation;
  45912. switch ( blendEquation ) {
  45913. case AddEquation:
  45914. blendOperation = GPUBlendOperation.Add;
  45915. break;
  45916. case SubtractEquation:
  45917. blendOperation = GPUBlendOperation.Subtract;
  45918. break;
  45919. case ReverseSubtractEquation:
  45920. blendOperation = GPUBlendOperation.ReverseSubtract;
  45921. break;
  45922. case MinEquation:
  45923. blendOperation = GPUBlendOperation.Min;
  45924. break;
  45925. case MaxEquation:
  45926. blendOperation = GPUBlendOperation.Max;
  45927. break;
  45928. default:
  45929. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  45930. }
  45931. return blendOperation;
  45932. }
  45933. /**
  45934. * Returns the primitive state as a descriptor object required
  45935. * for the pipeline creation.
  45936. *
  45937. * @private
  45938. * @param {Object3D} object - The 3D object.
  45939. * @param {BufferGeometry} geometry - The geometry.
  45940. * @param {Material} material - The material.
  45941. * @return {Object} The primitive state.
  45942. */
  45943. _getPrimitiveState( object, geometry, material ) {
  45944. const descriptor = {};
  45945. const utils = this.backend.utils;
  45946. descriptor.topology = utils.getPrimitiveTopology( object, material );
  45947. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  45948. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45949. }
  45950. switch ( material.side ) {
  45951. case FrontSide:
  45952. descriptor.frontFace = GPUFrontFace.CCW;
  45953. descriptor.cullMode = GPUCullMode.Back;
  45954. break;
  45955. case BackSide:
  45956. descriptor.frontFace = GPUFrontFace.CCW;
  45957. descriptor.cullMode = GPUCullMode.Front;
  45958. break;
  45959. case DoubleSide:
  45960. descriptor.frontFace = GPUFrontFace.CCW;
  45961. descriptor.cullMode = GPUCullMode.None;
  45962. break;
  45963. default:
  45964. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  45965. break;
  45966. }
  45967. return descriptor;
  45968. }
  45969. /**
  45970. * Returns the GPU color write mask which is required for the pipeline creation.
  45971. *
  45972. * @private
  45973. * @param {Material} material - The material.
  45974. * @return {String} The GPU color write mask.
  45975. */
  45976. _getColorWriteMask( material ) {
  45977. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  45978. }
  45979. /**
  45980. * Returns the GPU depth compare function which is required for the pipeline creation.
  45981. *
  45982. * @private
  45983. * @param {Material} material - The material.
  45984. * @return {String} The GPU depth compare function.
  45985. */
  45986. _getDepthCompare( material ) {
  45987. let depthCompare;
  45988. if ( material.depthTest === false ) {
  45989. depthCompare = GPUCompareFunction.Always;
  45990. } else {
  45991. const depthFunc = material.depthFunc;
  45992. switch ( depthFunc ) {
  45993. case NeverDepth:
  45994. depthCompare = GPUCompareFunction.Never;
  45995. break;
  45996. case AlwaysDepth:
  45997. depthCompare = GPUCompareFunction.Always;
  45998. break;
  45999. case LessDepth:
  46000. depthCompare = GPUCompareFunction.Less;
  46001. break;
  46002. case LessEqualDepth:
  46003. depthCompare = GPUCompareFunction.LessEqual;
  46004. break;
  46005. case EqualDepth:
  46006. depthCompare = GPUCompareFunction.Equal;
  46007. break;
  46008. case GreaterEqualDepth:
  46009. depthCompare = GPUCompareFunction.GreaterEqual;
  46010. break;
  46011. case GreaterDepth:
  46012. depthCompare = GPUCompareFunction.Greater;
  46013. break;
  46014. case NotEqualDepth:
  46015. depthCompare = GPUCompareFunction.NotEqual;
  46016. break;
  46017. default:
  46018. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  46019. }
  46020. }
  46021. return depthCompare;
  46022. }
  46023. }
  46024. /*// debugger tools
  46025. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  46026. //*/
  46027. /**
  46028. * A backend implementation targeting WebGPU.
  46029. *
  46030. * @private
  46031. * @augments Backend
  46032. */
  46033. class WebGPUBackend extends Backend {
  46034. /**
  46035. * Constructs a new WebGPU backend.
  46036. *
  46037. * @param {Object} parameters - The configuration parameter.
  46038. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46039. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46040. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46041. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46042. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46043. * @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.
  46044. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46045. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  46046. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  46047. * @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.
  46048. * @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.
  46049. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  46050. */
  46051. constructor( parameters = {} ) {
  46052. super( parameters );
  46053. /**
  46054. * This flag can be used for type testing.
  46055. *
  46056. * @type {Boolean}
  46057. * @readonly
  46058. * @default true
  46059. */
  46060. this.isWebGPUBackend = true;
  46061. // some parameters require default values other than "undefined"
  46062. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  46063. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  46064. /**
  46065. * Whether to track timestamps with a Timestamp Query API or not.
  46066. *
  46067. * @type {Boolean}
  46068. * @default false
  46069. */
  46070. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46071. /**
  46072. * A reference to the device.
  46073. *
  46074. * @type {GPUDevice?}
  46075. * @default null
  46076. */
  46077. this.device = null;
  46078. /**
  46079. * A reference to the context.
  46080. *
  46081. * @type {GPUCanvasContext?}
  46082. * @default null
  46083. */
  46084. this.context = null;
  46085. /**
  46086. * A reference to the color attachment of the default framebuffer.
  46087. *
  46088. * @type {GPUTexture?}
  46089. * @default null
  46090. */
  46091. this.colorBuffer = null;
  46092. /**
  46093. * A reference to the default render pass descriptor.
  46094. *
  46095. * @type {Object?}
  46096. * @default null
  46097. */
  46098. this.defaultRenderPassdescriptor = null;
  46099. /**
  46100. * A reference to a backend module holding common utility functions.
  46101. *
  46102. * @type {WebGPUUtils}
  46103. */
  46104. this.utils = new WebGPUUtils( this );
  46105. /**
  46106. * A reference to a backend module holding shader attribute-related
  46107. * utility functions.
  46108. *
  46109. * @type {WebGPUAttributeUtils}
  46110. */
  46111. this.attributeUtils = new WebGPUAttributeUtils( this );
  46112. /**
  46113. * A reference to a backend module holding shader binding-related
  46114. * utility functions.
  46115. *
  46116. * @type {WebGPUBindingUtils}
  46117. */
  46118. this.bindingUtils = new WebGPUBindingUtils( this );
  46119. /**
  46120. * A reference to a backend module holding shader pipeline-related
  46121. * utility functions.
  46122. *
  46123. * @type {WebGPUPipelineUtils}
  46124. */
  46125. this.pipelineUtils = new WebGPUPipelineUtils( this );
  46126. /**
  46127. * A reference to a backend module holding shader texture-related
  46128. * utility functions.
  46129. *
  46130. * @type {WebGPUTextureUtils}
  46131. */
  46132. this.textureUtils = new WebGPUTextureUtils( this );
  46133. /**
  46134. * A map that manages the resolve buffers for occlusion queries.
  46135. *
  46136. * @type {Map<Number,GPUBuffer>}
  46137. */
  46138. this.occludedResolveCache = new Map();
  46139. }
  46140. /**
  46141. * Initializes the backend so it is ready for usage.
  46142. *
  46143. * @async
  46144. * @param {Renderer} renderer - The renderer.
  46145. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46146. */
  46147. async init( renderer ) {
  46148. await super.init( renderer );
  46149. //
  46150. const parameters = this.parameters;
  46151. // create the device if it is not passed with parameters
  46152. let device;
  46153. if ( parameters.device === undefined ) {
  46154. const adapterOptions = {
  46155. powerPreference: parameters.powerPreference
  46156. };
  46157. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  46158. if ( adapter === null ) {
  46159. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  46160. }
  46161. // feature support
  46162. const features = Object.values( GPUFeatureName );
  46163. const supportedFeatures = [];
  46164. for ( const name of features ) {
  46165. if ( adapter.features.has( name ) ) {
  46166. supportedFeatures.push( name );
  46167. }
  46168. }
  46169. const deviceDescriptor = {
  46170. requiredFeatures: supportedFeatures,
  46171. requiredLimits: parameters.requiredLimits
  46172. };
  46173. device = await adapter.requestDevice( deviceDescriptor );
  46174. } else {
  46175. device = parameters.device;
  46176. }
  46177. device.lost.then( ( info ) => {
  46178. const deviceLossInfo = {
  46179. api: 'WebGPU',
  46180. message: info.message || 'Unknown reason',
  46181. reason: info.reason || null,
  46182. originalEvent: info
  46183. };
  46184. renderer.onDeviceLost( deviceLossInfo );
  46185. } );
  46186. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  46187. this.device = device;
  46188. this.context = context;
  46189. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  46190. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  46191. this.context.configure( {
  46192. device: this.device,
  46193. format: this.utils.getPreferredCanvasFormat(),
  46194. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  46195. alphaMode: alphaMode
  46196. } );
  46197. this.updateSize();
  46198. }
  46199. /**
  46200. * The coordinate system of the backend.
  46201. *
  46202. * @type {Number}
  46203. * @readonly
  46204. */
  46205. get coordinateSystem() {
  46206. return WebGPUCoordinateSystem;
  46207. }
  46208. /**
  46209. * This method performs a readback operation by moving buffer data from
  46210. * a storage buffer attribute from the GPU to the CPU.
  46211. *
  46212. * @async
  46213. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46214. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46215. */
  46216. async getArrayBufferAsync( attribute ) {
  46217. return await this.attributeUtils.getArrayBufferAsync( attribute );
  46218. }
  46219. /**
  46220. * Returns the backend's rendering context.
  46221. *
  46222. * @return {GPUCanvasContext} The rendering context.
  46223. */
  46224. getContext() {
  46225. return this.context;
  46226. }
  46227. /**
  46228. * Returns the default render pass descriptor.
  46229. *
  46230. * In WebGPU, the default framebuffer must be configured
  46231. * like custom framebuffers so the backend needs a render
  46232. * pass descriptor even when rendering directly to screen.
  46233. *
  46234. * @private
  46235. * @return {Object} The render pass descriptor.
  46236. */
  46237. _getDefaultRenderPassDescriptor() {
  46238. let descriptor = this.defaultRenderPassdescriptor;
  46239. if ( descriptor === null ) {
  46240. const renderer = this.renderer;
  46241. descriptor = {
  46242. colorAttachments: [ {
  46243. view: null
  46244. } ],
  46245. };
  46246. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  46247. descriptor.depthStencilAttachment = {
  46248. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  46249. };
  46250. }
  46251. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46252. if ( this.renderer.samples > 0 ) {
  46253. colorAttachment.view = this.colorBuffer.createView();
  46254. } else {
  46255. colorAttachment.resolveTarget = undefined;
  46256. }
  46257. this.defaultRenderPassdescriptor = descriptor;
  46258. }
  46259. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46260. if ( this.renderer.samples > 0 ) {
  46261. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  46262. } else {
  46263. colorAttachment.view = this.context.getCurrentTexture().createView();
  46264. }
  46265. return descriptor;
  46266. }
  46267. /**
  46268. * Returns the render pass descriptor for the given render context.
  46269. *
  46270. * @private
  46271. * @param {RenderContext} renderContext - The render context.
  46272. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  46273. * @return {Object} The render pass descriptor.
  46274. */
  46275. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  46276. const renderTarget = renderContext.renderTarget;
  46277. const renderTargetData = this.get( renderTarget );
  46278. let descriptors = renderTargetData.descriptors;
  46279. if ( descriptors === undefined ||
  46280. renderTargetData.width !== renderTarget.width ||
  46281. renderTargetData.height !== renderTarget.height ||
  46282. renderTargetData.dimensions !== renderTarget.dimensions ||
  46283. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  46284. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  46285. renderTargetData.samples !== renderTarget.samples ||
  46286. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  46287. ) {
  46288. descriptors = {};
  46289. renderTargetData.descriptors = descriptors;
  46290. // dispose
  46291. const onDispose = () => {
  46292. renderTarget.removeEventListener( 'dispose', onDispose );
  46293. this.delete( renderTarget );
  46294. };
  46295. renderTarget.addEventListener( 'dispose', onDispose );
  46296. }
  46297. const cacheKey = renderContext.getCacheKey();
  46298. let descriptor = descriptors[ cacheKey ];
  46299. if ( descriptor === undefined ) {
  46300. const textures = renderContext.textures;
  46301. const colorAttachments = [];
  46302. let sliceIndex;
  46303. for ( let i = 0; i < textures.length; i ++ ) {
  46304. const textureData = this.get( textures[ i ] );
  46305. const viewDescriptor = {
  46306. label: `colorAttachment_${ i }`,
  46307. baseMipLevel: renderContext.activeMipmapLevel,
  46308. mipLevelCount: 1,
  46309. baseArrayLayer: renderContext.activeCubeFace,
  46310. arrayLayerCount: 1,
  46311. dimension: GPUTextureViewDimension.TwoD
  46312. };
  46313. if ( renderTarget.isRenderTarget3D ) {
  46314. sliceIndex = renderContext.activeCubeFace;
  46315. viewDescriptor.baseArrayLayer = 0;
  46316. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  46317. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46318. } else if ( renderTarget.isRenderTargetArray ) {
  46319. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  46320. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46321. }
  46322. const textureView = textureData.texture.createView( viewDescriptor );
  46323. let view, resolveTarget;
  46324. if ( textureData.msaaTexture !== undefined ) {
  46325. view = textureData.msaaTexture.createView();
  46326. resolveTarget = textureView;
  46327. } else {
  46328. view = textureView;
  46329. resolveTarget = undefined;
  46330. }
  46331. colorAttachments.push( {
  46332. view,
  46333. depthSlice: sliceIndex,
  46334. resolveTarget,
  46335. loadOp: GPULoadOp.Load,
  46336. storeOp: GPUStoreOp.Store,
  46337. ...colorAttachmentsConfig
  46338. } );
  46339. }
  46340. descriptor = {
  46341. colorAttachments,
  46342. };
  46343. if ( renderContext.depth ) {
  46344. const depthTextureData = this.get( renderContext.depthTexture );
  46345. const depthStencilAttachment = {
  46346. view: depthTextureData.texture.createView()
  46347. };
  46348. descriptor.depthStencilAttachment = depthStencilAttachment;
  46349. }
  46350. descriptors[ cacheKey ] = descriptor;
  46351. renderTargetData.width = renderTarget.width;
  46352. renderTargetData.height = renderTarget.height;
  46353. renderTargetData.samples = renderTarget.samples;
  46354. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  46355. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  46356. renderTargetData.dimensions = renderTarget.dimensions;
  46357. renderTargetData.depthSlice = sliceIndex;
  46358. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  46359. }
  46360. return descriptor;
  46361. }
  46362. /**
  46363. * This method is executed at the beginning of a render call and prepares
  46364. * the WebGPU state for upcoming render calls
  46365. *
  46366. * @param {RenderContext} renderContext - The render context.
  46367. */
  46368. beginRender( renderContext ) {
  46369. const renderContextData = this.get( renderContext );
  46370. const device = this.device;
  46371. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46372. let occlusionQuerySet;
  46373. if ( occlusionQueryCount > 0 ) {
  46374. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  46375. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  46376. // Get a reference to the array of objects with queries. The renderContextData property
  46377. // can be changed by another render pass before the buffer.mapAsyc() completes.
  46378. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  46379. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  46380. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  46381. //
  46382. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  46383. renderContextData.occlusionQuerySet = occlusionQuerySet;
  46384. renderContextData.occlusionQueryIndex = 0;
  46385. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  46386. renderContextData.lastOcclusionObject = null;
  46387. }
  46388. let descriptor;
  46389. if ( renderContext.textures === null ) {
  46390. descriptor = this._getDefaultRenderPassDescriptor();
  46391. } else {
  46392. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  46393. }
  46394. this.initTimestampQuery( renderContext, descriptor );
  46395. descriptor.occlusionQuerySet = occlusionQuerySet;
  46396. const depthStencilAttachment = descriptor.depthStencilAttachment;
  46397. if ( renderContext.textures !== null ) {
  46398. const colorAttachments = descriptor.colorAttachments;
  46399. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  46400. const colorAttachment = colorAttachments[ i ];
  46401. if ( renderContext.clearColor ) {
  46402. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  46403. colorAttachment.loadOp = GPULoadOp.Clear;
  46404. colorAttachment.storeOp = GPUStoreOp.Store;
  46405. } else {
  46406. colorAttachment.loadOp = GPULoadOp.Load;
  46407. colorAttachment.storeOp = GPUStoreOp.Store;
  46408. }
  46409. }
  46410. } else {
  46411. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46412. if ( renderContext.clearColor ) {
  46413. colorAttachment.clearValue = renderContext.clearColorValue;
  46414. colorAttachment.loadOp = GPULoadOp.Clear;
  46415. colorAttachment.storeOp = GPUStoreOp.Store;
  46416. } else {
  46417. colorAttachment.loadOp = GPULoadOp.Load;
  46418. colorAttachment.storeOp = GPUStoreOp.Store;
  46419. }
  46420. }
  46421. //
  46422. if ( renderContext.depth ) {
  46423. if ( renderContext.clearDepth ) {
  46424. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  46425. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46426. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46427. } else {
  46428. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46429. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46430. }
  46431. }
  46432. if ( renderContext.stencil ) {
  46433. if ( renderContext.clearStencil ) {
  46434. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  46435. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46436. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46437. } else {
  46438. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46439. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46440. }
  46441. }
  46442. //
  46443. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  46444. const currentPass = encoder.beginRenderPass( descriptor );
  46445. //
  46446. renderContextData.descriptor = descriptor;
  46447. renderContextData.encoder = encoder;
  46448. renderContextData.currentPass = currentPass;
  46449. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46450. renderContextData.renderBundles = [];
  46451. //
  46452. if ( renderContext.viewport ) {
  46453. this.updateViewport( renderContext );
  46454. }
  46455. if ( renderContext.scissor ) {
  46456. const { x, y, width, height } = renderContext.scissorValue;
  46457. currentPass.setScissorRect( x, y, width, height );
  46458. }
  46459. }
  46460. /**
  46461. * This method is executed at the end of a render call and finalizes work
  46462. * after draw calls.
  46463. *
  46464. * @param {RenderContext} renderContext - The render context.
  46465. */
  46466. finishRender( renderContext ) {
  46467. const renderContextData = this.get( renderContext );
  46468. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46469. if ( renderContextData.renderBundles.length > 0 ) {
  46470. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  46471. }
  46472. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  46473. renderContextData.currentPass.endOcclusionQuery();
  46474. }
  46475. renderContextData.currentPass.end();
  46476. if ( occlusionQueryCount > 0 ) {
  46477. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  46478. //
  46479. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  46480. if ( queryResolveBuffer === undefined ) {
  46481. queryResolveBuffer = this.device.createBuffer(
  46482. {
  46483. size: bufferSize,
  46484. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  46485. }
  46486. );
  46487. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  46488. }
  46489. //
  46490. const readBuffer = this.device.createBuffer(
  46491. {
  46492. size: bufferSize,
  46493. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46494. }
  46495. );
  46496. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  46497. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  46498. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  46499. renderContextData.occlusionQueryBuffer = readBuffer;
  46500. //
  46501. this.resolveOccludedAsync( renderContext );
  46502. }
  46503. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  46504. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  46505. //
  46506. if ( renderContext.textures !== null ) {
  46507. const textures = renderContext.textures;
  46508. for ( let i = 0; i < textures.length; i ++ ) {
  46509. const texture = textures[ i ];
  46510. if ( texture.generateMipmaps === true ) {
  46511. this.textureUtils.generateMipmaps( texture );
  46512. }
  46513. }
  46514. }
  46515. }
  46516. /**
  46517. * Returns `true` if the given 3D object is fully occluded by other
  46518. * 3D objects in the scene.
  46519. *
  46520. * @param {RenderContext} renderContext - The render context.
  46521. * @param {Object3D} object - The 3D object to test.
  46522. * @return {Boolean} Whether the 3D object is fully occluded or not.
  46523. */
  46524. isOccluded( renderContext, object ) {
  46525. const renderContextData = this.get( renderContext );
  46526. return renderContextData.occluded && renderContextData.occluded.has( object );
  46527. }
  46528. /**
  46529. * This method processes the result of occlusion queries and writes it
  46530. * into render context data.
  46531. *
  46532. * @async
  46533. * @param {RenderContext} renderContext - The render context.
  46534. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  46535. */
  46536. async resolveOccludedAsync( renderContext ) {
  46537. const renderContextData = this.get( renderContext );
  46538. // handle occlusion query results
  46539. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  46540. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  46541. const occluded = new WeakSet();
  46542. renderContextData.currentOcclusionQueryObjects = null;
  46543. renderContextData.currentOcclusionQueryBuffer = null;
  46544. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  46545. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  46546. const results = new BigUint64Array( buffer );
  46547. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  46548. if ( results[ i ] === BigInt( 0 ) ) {
  46549. occluded.add( currentOcclusionQueryObjects[ i ] );
  46550. }
  46551. }
  46552. currentOcclusionQueryBuffer.destroy();
  46553. renderContextData.occluded = occluded;
  46554. }
  46555. }
  46556. /**
  46557. * Updates the viewport with the values from the given render context.
  46558. *
  46559. * @param {RenderContext} renderContext - The render context.
  46560. */
  46561. updateViewport( renderContext ) {
  46562. const { currentPass } = this.get( renderContext );
  46563. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  46564. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  46565. }
  46566. /**
  46567. * Performs a clear operation.
  46568. *
  46569. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  46570. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  46571. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  46572. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  46573. */
  46574. clear( color, depth, stencil, renderTargetContext = null ) {
  46575. const device = this.device;
  46576. const renderer = this.renderer;
  46577. let colorAttachments = [];
  46578. let depthStencilAttachment;
  46579. let clearValue;
  46580. let supportsDepth;
  46581. let supportsStencil;
  46582. if ( color ) {
  46583. const clearColor = this.getClearColor();
  46584. if ( this.renderer.alpha === true ) {
  46585. // premultiply alpha
  46586. const a = clearColor.a;
  46587. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  46588. } else {
  46589. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  46590. }
  46591. }
  46592. if ( renderTargetContext === null ) {
  46593. supportsDepth = renderer.depth;
  46594. supportsStencil = renderer.stencil;
  46595. const descriptor = this._getDefaultRenderPassDescriptor();
  46596. if ( color ) {
  46597. colorAttachments = descriptor.colorAttachments;
  46598. const colorAttachment = colorAttachments[ 0 ];
  46599. colorAttachment.clearValue = clearValue;
  46600. colorAttachment.loadOp = GPULoadOp.Clear;
  46601. colorAttachment.storeOp = GPUStoreOp.Store;
  46602. }
  46603. if ( supportsDepth || supportsStencil ) {
  46604. depthStencilAttachment = descriptor.depthStencilAttachment;
  46605. }
  46606. } else {
  46607. supportsDepth = renderTargetContext.depth;
  46608. supportsStencil = renderTargetContext.stencil;
  46609. if ( color ) {
  46610. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  46611. colorAttachments = descriptor.colorAttachments;
  46612. }
  46613. if ( supportsDepth || supportsStencil ) {
  46614. const depthTextureData = this.get( renderTargetContext.depthTexture );
  46615. depthStencilAttachment = {
  46616. view: depthTextureData.texture.createView()
  46617. };
  46618. }
  46619. }
  46620. //
  46621. if ( supportsDepth ) {
  46622. if ( depth ) {
  46623. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46624. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  46625. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46626. } else {
  46627. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46628. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46629. }
  46630. }
  46631. //
  46632. if ( supportsStencil ) {
  46633. if ( stencil ) {
  46634. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46635. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  46636. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46637. } else {
  46638. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46639. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46640. }
  46641. }
  46642. //
  46643. const encoder = device.createCommandEncoder( { label: 'clear' } );
  46644. const currentPass = encoder.beginRenderPass( {
  46645. colorAttachments,
  46646. depthStencilAttachment
  46647. } );
  46648. currentPass.end();
  46649. device.queue.submit( [ encoder.finish() ] );
  46650. }
  46651. // compute
  46652. /**
  46653. * This method is executed at the beginning of a compute call and
  46654. * prepares the state for upcoming compute tasks.
  46655. *
  46656. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46657. */
  46658. beginCompute( computeGroup ) {
  46659. const groupGPU = this.get( computeGroup );
  46660. const descriptor = {
  46661. label: 'computeGroup_' + computeGroup.id
  46662. };
  46663. this.initTimestampQuery( computeGroup, descriptor );
  46664. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  46665. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  46666. }
  46667. /**
  46668. * Executes a compute command for the given compute node.
  46669. *
  46670. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46671. * @param {Node} computeNode - The compute node.
  46672. * @param {Array<BindGroup>} bindings - The bindings.
  46673. * @param {ComputePipeline} pipeline - The compute pipeline.
  46674. */
  46675. compute( computeGroup, computeNode, bindings, pipeline ) {
  46676. const { passEncoderGPU } = this.get( computeGroup );
  46677. // pipeline
  46678. const pipelineGPU = this.get( pipeline ).pipeline;
  46679. passEncoderGPU.setPipeline( pipelineGPU );
  46680. // bind groups
  46681. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46682. const bindGroup = bindings[ i ];
  46683. const bindingsData = this.get( bindGroup );
  46684. passEncoderGPU.setBindGroup( i, bindingsData.group );
  46685. }
  46686. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  46687. const computeNodeData = this.get( computeNode );
  46688. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  46689. const { dispatchSize } = computeNodeData;
  46690. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  46691. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  46692. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  46693. } else {
  46694. dispatchSize.x = computeNode.dispatchCount;
  46695. }
  46696. passEncoderGPU.dispatchWorkgroups(
  46697. dispatchSize.x,
  46698. dispatchSize.y,
  46699. dispatchSize.z
  46700. );
  46701. }
  46702. /**
  46703. * This method is executed at the end of a compute call and
  46704. * finalizes work after compute tasks.
  46705. *
  46706. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46707. */
  46708. finishCompute( computeGroup ) {
  46709. const groupData = this.get( computeGroup );
  46710. groupData.passEncoderGPU.end();
  46711. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  46712. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  46713. }
  46714. /**
  46715. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  46716. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  46717. *
  46718. * @async
  46719. * @return {Promise} A Promise that resolves when synchronization has been finished.
  46720. */
  46721. async waitForGPU() {
  46722. await this.device.queue.onSubmittedWorkDone();
  46723. }
  46724. // render object
  46725. /**
  46726. * Executes a draw command for the given render object.
  46727. *
  46728. * @param {RenderObject} renderObject - The render object to draw.
  46729. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46730. */
  46731. draw( renderObject, info ) {
  46732. const { object, context, pipeline } = renderObject;
  46733. const bindings = renderObject.getBindings();
  46734. const renderContextData = this.get( context );
  46735. const pipelineGPU = this.get( pipeline ).pipeline;
  46736. const currentSets = renderContextData.currentSets;
  46737. const passEncoderGPU = renderContextData.currentPass;
  46738. const drawParams = renderObject.getDrawParameters();
  46739. if ( drawParams === null ) return;
  46740. // pipeline
  46741. if ( currentSets.pipeline !== pipelineGPU ) {
  46742. passEncoderGPU.setPipeline( pipelineGPU );
  46743. currentSets.pipeline = pipelineGPU;
  46744. }
  46745. // bind groups
  46746. const currentBindingGroups = currentSets.bindingGroups;
  46747. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46748. const bindGroup = bindings[ i ];
  46749. const bindingsData = this.get( bindGroup );
  46750. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  46751. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  46752. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  46753. }
  46754. }
  46755. // attributes
  46756. const index = renderObject.getIndex();
  46757. const hasIndex = ( index !== null );
  46758. // index
  46759. if ( hasIndex === true ) {
  46760. if ( currentSets.index !== index ) {
  46761. const buffer = this.get( index ).buffer;
  46762. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46763. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  46764. currentSets.index = index;
  46765. }
  46766. }
  46767. // vertex buffers
  46768. const vertexBuffers = renderObject.getVertexBuffers();
  46769. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  46770. const vertexBuffer = vertexBuffers[ i ];
  46771. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  46772. const buffer = this.get( vertexBuffer ).buffer;
  46773. passEncoderGPU.setVertexBuffer( i, buffer );
  46774. currentSets.attributes[ i ] = vertexBuffer;
  46775. }
  46776. }
  46777. // occlusion queries - handle multiple consecutive draw calls for an object
  46778. if ( renderContextData.occlusionQuerySet !== undefined ) {
  46779. const lastObject = renderContextData.lastOcclusionObject;
  46780. if ( lastObject !== object ) {
  46781. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46782. passEncoderGPU.endOcclusionQuery();
  46783. renderContextData.occlusionQueryIndex ++;
  46784. }
  46785. if ( object.occlusionTest === true ) {
  46786. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  46787. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  46788. }
  46789. renderContextData.lastOcclusionObject = object;
  46790. }
  46791. }
  46792. // draw
  46793. const draw = () => {
  46794. if ( object.isBatchedMesh === true ) {
  46795. const starts = object._multiDrawStarts;
  46796. const counts = object._multiDrawCounts;
  46797. const drawCount = object._multiDrawCount;
  46798. const drawInstances = object._multiDrawInstances;
  46799. for ( let i = 0; i < drawCount; i ++ ) {
  46800. const count = drawInstances ? drawInstances[ i ] : 1;
  46801. const firstInstance = count > 1 ? 0 : i;
  46802. if ( hasIndex === true ) {
  46803. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  46804. } else {
  46805. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  46806. }
  46807. }
  46808. } else if ( hasIndex === true ) {
  46809. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  46810. const indirect = renderObject.getIndirect();
  46811. if ( indirect !== null ) {
  46812. const buffer = this.get( indirect ).buffer;
  46813. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  46814. } else {
  46815. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  46816. }
  46817. info.update( object, indexCount, instanceCount );
  46818. } else {
  46819. const { vertexCount, instanceCount, firstVertex } = drawParams;
  46820. const indirect = renderObject.getIndirect();
  46821. if ( indirect !== null ) {
  46822. const buffer = this.get( indirect ).buffer;
  46823. passEncoderGPU.drawIndirect( buffer, 0 );
  46824. } else {
  46825. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  46826. }
  46827. info.update( object, vertexCount, instanceCount );
  46828. }
  46829. };
  46830. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  46831. const cameraData = this.get( renderObject.camera );
  46832. const cameras = renderObject.camera.cameras;
  46833. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  46834. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  46835. const bindingsData = this.get( cameraIndex );
  46836. const indexesGPU = [];
  46837. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  46838. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46839. data[ 0 ] = i;
  46840. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  46841. indexesGPU.push( bindGroupIndex );
  46842. }
  46843. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  46844. }
  46845. const pixelRatio = this.renderer.getPixelRatio();
  46846. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46847. const subCamera = cameras[ i ];
  46848. if ( object.layers.test( subCamera.layers ) ) {
  46849. const vp = subCamera.viewport;
  46850. passEncoderGPU.setViewport(
  46851. Math.floor( vp.x * pixelRatio ),
  46852. Math.floor( vp.y * pixelRatio ),
  46853. Math.floor( vp.width * pixelRatio ),
  46854. Math.floor( vp.height * pixelRatio ),
  46855. context.viewportValue.minDepth,
  46856. context.viewportValue.maxDepth
  46857. );
  46858. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  46859. draw();
  46860. }
  46861. }
  46862. } else {
  46863. draw();
  46864. }
  46865. }
  46866. // cache key
  46867. /**
  46868. * Returns `true` if the render pipeline requires an update.
  46869. *
  46870. * @param {RenderObject} renderObject - The render object.
  46871. * @return {Boolean} Whether the render pipeline requires an update or not.
  46872. */
  46873. needsRenderUpdate( renderObject ) {
  46874. const data = this.get( renderObject );
  46875. const { object, material } = renderObject;
  46876. const utils = this.utils;
  46877. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  46878. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  46879. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46880. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46881. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  46882. let needsUpdate = false;
  46883. if ( data.material !== material || data.materialVersion !== material.version ||
  46884. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  46885. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  46886. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  46887. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  46888. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  46889. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  46890. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  46891. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  46892. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  46893. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  46894. data.primitiveTopology !== primitiveTopology ||
  46895. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  46896. ) {
  46897. data.material = material; data.materialVersion = material.version;
  46898. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  46899. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  46900. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  46901. data.colorWrite = material.colorWrite;
  46902. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  46903. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  46904. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  46905. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  46906. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  46907. data.sampleCount = sampleCount;
  46908. data.colorSpace = colorSpace;
  46909. data.colorFormat = colorFormat;
  46910. data.depthStencilFormat = depthStencilFormat;
  46911. data.primitiveTopology = primitiveTopology;
  46912. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  46913. needsUpdate = true;
  46914. }
  46915. return needsUpdate;
  46916. }
  46917. /**
  46918. * Returns a cache key that is used to identify render pipelines.
  46919. *
  46920. * @param {RenderObject} renderObject - The render object.
  46921. * @return {String} The cache key.
  46922. */
  46923. getRenderCacheKey( renderObject ) {
  46924. const { object, material } = renderObject;
  46925. const utils = this.utils;
  46926. const renderContext = renderObject.context;
  46927. return [
  46928. material.transparent, material.blending, material.premultipliedAlpha,
  46929. material.blendSrc, material.blendDst, material.blendEquation,
  46930. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  46931. material.colorWrite,
  46932. material.depthWrite, material.depthTest, material.depthFunc,
  46933. material.stencilWrite, material.stencilFunc,
  46934. material.stencilFail, material.stencilZFail, material.stencilZPass,
  46935. material.stencilFuncMask, material.stencilWriteMask,
  46936. material.side,
  46937. utils.getSampleCountRenderContext( renderContext ),
  46938. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  46939. utils.getPrimitiveTopology( object, material ),
  46940. renderObject.getGeometryCacheKey(),
  46941. renderObject.clippingContextCacheKey
  46942. ].join();
  46943. }
  46944. // textures
  46945. /**
  46946. * Creates a GPU sampler for the given texture.
  46947. *
  46948. * @param {Texture} texture - The texture to create the sampler for.
  46949. */
  46950. createSampler( texture ) {
  46951. this.textureUtils.createSampler( texture );
  46952. }
  46953. /**
  46954. * Destroys the GPU sampler for the given texture.
  46955. *
  46956. * @param {Texture} texture - The texture to destroy the sampler for.
  46957. */
  46958. destroySampler( texture ) {
  46959. this.textureUtils.destroySampler( texture );
  46960. }
  46961. /**
  46962. * Creates a default texture for the given texture that can be used
  46963. * as a placeholder until the actual texture is ready for usage.
  46964. *
  46965. * @param {Texture} texture - The texture to create a default texture for.
  46966. */
  46967. createDefaultTexture( texture ) {
  46968. this.textureUtils.createDefaultTexture( texture );
  46969. }
  46970. /**
  46971. * Defines a texture on the GPU for the given texture object.
  46972. *
  46973. * @param {Texture} texture - The texture.
  46974. * @param {Object} [options={}] - Optional configuration parameter.
  46975. */
  46976. createTexture( texture, options ) {
  46977. this.textureUtils.createTexture( texture, options );
  46978. }
  46979. /**
  46980. * Uploads the updated texture data to the GPU.
  46981. *
  46982. * @param {Texture} texture - The texture.
  46983. * @param {Object} [options={}] - Optional configuration parameter.
  46984. */
  46985. updateTexture( texture, options ) {
  46986. this.textureUtils.updateTexture( texture, options );
  46987. }
  46988. /**
  46989. * Generates mipmaps for the given texture.
  46990. *
  46991. * @param {Texture} texture - The texture.
  46992. */
  46993. generateMipmaps( texture ) {
  46994. this.textureUtils.generateMipmaps( texture );
  46995. }
  46996. /**
  46997. * Destroys the GPU data for the given texture object.
  46998. *
  46999. * @param {Texture} texture - The texture.
  47000. */
  47001. destroyTexture( texture ) {
  47002. this.textureUtils.destroyTexture( texture );
  47003. }
  47004. /**
  47005. * Returns texture data as a typed array.
  47006. *
  47007. * @async
  47008. * @param {Texture} texture - The texture to copy.
  47009. * @param {Number} x - The x coordinate of the copy origin.
  47010. * @param {Number} y - The y coordinate of the copy origin.
  47011. * @param {Number} width - The width of the copy.
  47012. * @param {Number} height - The height of the copy.
  47013. * @param {Number} faceIndex - The face index.
  47014. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47015. */
  47016. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47017. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47018. }
  47019. /**
  47020. * Inits a time stamp query for the given render context.
  47021. *
  47022. * @param {RenderContext} renderContext - The render context.
  47023. * @param {Object} descriptor - The query descriptor.
  47024. */
  47025. initTimestampQuery( renderContext, descriptor ) {
  47026. if ( ! this.trackTimestamp ) return;
  47027. const renderContextData = this.get( renderContext );
  47028. // init query set if not exists
  47029. if ( ! renderContextData.timestampQuerySet ) {
  47030. const type = renderContext.isComputeNode ? 'compute' : 'render';
  47031. renderContextData.timestampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  47032. }
  47033. // augment descriptor
  47034. descriptor.timestampWrites = {
  47035. querySet: renderContextData.timestampQuerySet,
  47036. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  47037. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  47038. };
  47039. }
  47040. /**
  47041. * Prepares the timestamp buffer.
  47042. *
  47043. * @param {RenderContext} renderContext - The render context.
  47044. * @param {GPUCommandEncoder} encoder - The command encoder.
  47045. */
  47046. prepareTimestampBuffer( renderContext, encoder ) {
  47047. if ( ! this.trackTimestamp ) return;
  47048. const renderContextData = this.get( renderContext );
  47049. const size = 2 * BigUint64Array.BYTES_PER_ELEMENT;
  47050. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  47051. renderContextData.currentTimestampQueryBuffers = {
  47052. resolveBuffer: this.device.createBuffer( {
  47053. label: 'timestamp resolve buffer',
  47054. size: size,
  47055. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  47056. } ),
  47057. resultBuffer: this.device.createBuffer( {
  47058. label: 'timestamp result buffer',
  47059. size: size,
  47060. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  47061. } )
  47062. };
  47063. }
  47064. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47065. encoder.resolveQuerySet( renderContextData.timestampQuerySet, 0, 2, resolveBuffer, 0 );
  47066. if ( resultBuffer.mapState === 'unmapped' ) {
  47067. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  47068. }
  47069. }
  47070. /**
  47071. * Resolves the time stamp for the given render context and type.
  47072. *
  47073. * @async
  47074. * @param {RenderContext} renderContext - The render context.
  47075. * @param {String} type - The render context.
  47076. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  47077. */
  47078. async resolveTimestampAsync( renderContext, type = 'render' ) {
  47079. if ( ! this.trackTimestamp ) return;
  47080. const renderContextData = this.get( renderContext );
  47081. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  47082. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47083. if ( resultBuffer.mapState === 'unmapped' ) {
  47084. await resultBuffer.mapAsync( GPUMapMode.READ );
  47085. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  47086. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  47087. this.renderer.info.updateTimestamp( type, duration );
  47088. resultBuffer.unmap();
  47089. }
  47090. }
  47091. // node builder
  47092. /**
  47093. * Returns a node builder for the given render object.
  47094. *
  47095. * @param {RenderObject} object - The render object.
  47096. * @param {Renderer} renderer - The renderer.
  47097. * @return {WGSLNodeBuilder} The node builder.
  47098. */
  47099. createNodeBuilder( object, renderer ) {
  47100. return new WGSLNodeBuilder( object, renderer );
  47101. }
  47102. // program
  47103. /**
  47104. * Creates a shader program from the given programmable stage.
  47105. *
  47106. * @param {ProgrammableStage} program - The programmable stage.
  47107. */
  47108. createProgram( program ) {
  47109. const programGPU = this.get( program );
  47110. programGPU.module = {
  47111. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  47112. entryPoint: 'main'
  47113. };
  47114. }
  47115. /**
  47116. * Destroys the shader program of the given programmable stage.
  47117. *
  47118. * @param {ProgrammableStage} program - The programmable stage.
  47119. */
  47120. destroyProgram( program ) {
  47121. this.delete( program );
  47122. }
  47123. // pipelines
  47124. /**
  47125. * Creates a render pipeline for the given render object.
  47126. *
  47127. * @param {RenderObject} renderObject - The render object.
  47128. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47129. */
  47130. createRenderPipeline( renderObject, promises ) {
  47131. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  47132. }
  47133. /**
  47134. * Creates a compute pipeline for the given compute node.
  47135. *
  47136. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47137. * @param {Array<BindGroup>} bindings - The bindings.
  47138. */
  47139. createComputePipeline( computePipeline, bindings ) {
  47140. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  47141. }
  47142. /**
  47143. * Prepares the state for encoding render bundles.
  47144. *
  47145. * @param {RenderContext} renderContext - The render context.
  47146. */
  47147. beginBundle( renderContext ) {
  47148. const renderContextData = this.get( renderContext );
  47149. renderContextData._currentPass = renderContextData.currentPass;
  47150. renderContextData._currentSets = renderContextData.currentSets;
  47151. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47152. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  47153. }
  47154. /**
  47155. * After processing render bundles this method finalizes related work.
  47156. *
  47157. * @param {RenderContext} renderContext - The render context.
  47158. * @param {RenderBundle} bundle - The render bundle.
  47159. */
  47160. finishBundle( renderContext, bundle ) {
  47161. const renderContextData = this.get( renderContext );
  47162. const bundleEncoder = renderContextData.currentPass;
  47163. const bundleGPU = bundleEncoder.finish();
  47164. this.get( bundle ).bundleGPU = bundleGPU;
  47165. // restore render pass state
  47166. renderContextData.currentSets = renderContextData._currentSets;
  47167. renderContextData.currentPass = renderContextData._currentPass;
  47168. }
  47169. /**
  47170. * Adds a render bundle to the render context data.
  47171. *
  47172. * @param {RenderContext} renderContext - The render context.
  47173. * @param {RenderBundle} bundle - The render bundle to add.
  47174. */
  47175. addBundle( renderContext, bundle ) {
  47176. const renderContextData = this.get( renderContext );
  47177. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  47178. }
  47179. // bindings
  47180. /**
  47181. * Creates bindings from the given bind group definition.
  47182. *
  47183. * @param {BindGroup} bindGroup - The bind group.
  47184. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47185. * @param {Number} cacheIndex - The cache index.
  47186. * @param {Number} version - The version.
  47187. */
  47188. createBindings( bindGroup, bindings, cacheIndex, version ) {
  47189. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47190. }
  47191. /**
  47192. * Updates the given bind group definition.
  47193. *
  47194. * @param {BindGroup} bindGroup - The bind group.
  47195. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47196. * @param {Number} cacheIndex - The cache index.
  47197. * @param {Number} version - The version.
  47198. */
  47199. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  47200. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47201. }
  47202. /**
  47203. * Updates a buffer binding.
  47204. *
  47205. * @param {Buffer} binding - The buffer binding to update.
  47206. */
  47207. updateBinding( binding ) {
  47208. this.bindingUtils.updateBinding( binding );
  47209. }
  47210. // attributes
  47211. /**
  47212. * Creates the buffer of an indexed shader attribute.
  47213. *
  47214. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47215. */
  47216. createIndexAttribute( attribute ) {
  47217. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47218. }
  47219. /**
  47220. * Creates the GPU buffer of a shader attribute.
  47221. *
  47222. * @param {BufferAttribute} attribute - The buffer attribute.
  47223. */
  47224. createAttribute( attribute ) {
  47225. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47226. }
  47227. /**
  47228. * Creates the GPU buffer of a storage attribute.
  47229. *
  47230. * @param {BufferAttribute} attribute - The buffer attribute.
  47231. */
  47232. createStorageAttribute( attribute ) {
  47233. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47234. }
  47235. /**
  47236. * Creates the GPU buffer of an indirect storage attribute.
  47237. *
  47238. * @param {BufferAttribute} attribute - The buffer attribute.
  47239. */
  47240. createIndirectStorageAttribute( attribute ) {
  47241. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47242. }
  47243. /**
  47244. * Updates the GPU buffer of a shader attribute.
  47245. *
  47246. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47247. */
  47248. updateAttribute( attribute ) {
  47249. this.attributeUtils.updateAttribute( attribute );
  47250. }
  47251. /**
  47252. * Destroys the GPU buffer of a shader attribute.
  47253. *
  47254. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47255. */
  47256. destroyAttribute( attribute ) {
  47257. this.attributeUtils.destroyAttribute( attribute );
  47258. }
  47259. // canvas
  47260. /**
  47261. * Triggers an update of the default render pass descriptor.
  47262. */
  47263. updateSize() {
  47264. this.colorBuffer = this.textureUtils.getColorBuffer();
  47265. this.defaultRenderPassdescriptor = null;
  47266. }
  47267. // utils public
  47268. /**
  47269. * Returns the maximum anisotropy texture filtering value.
  47270. *
  47271. * @return {Number} The maximum anisotropy texture filtering value.
  47272. */
  47273. getMaxAnisotropy() {
  47274. return 16;
  47275. }
  47276. /**
  47277. * Checks if the given feature is supported by the backend.
  47278. *
  47279. * @param {String} name - The feature's name.
  47280. * @return {Boolean} Whether the feature is supported or not.
  47281. */
  47282. hasFeature( name ) {
  47283. return this.device.features.has( name );
  47284. }
  47285. /**
  47286. * Copies data of the given source texture to the given destination texture.
  47287. *
  47288. * @param {Texture} srcTexture - The source texture.
  47289. * @param {Texture} dstTexture - The destination texture.
  47290. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  47291. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  47292. * @param {Number} [level=0] - The mip level to copy.
  47293. */
  47294. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  47295. let dstX = 0;
  47296. let dstY = 0;
  47297. let dstLayer = 0;
  47298. let srcX = 0;
  47299. let srcY = 0;
  47300. let srcLayer = 0;
  47301. let srcWidth = srcTexture.image.width;
  47302. let srcHeight = srcTexture.image.height;
  47303. if ( srcRegion !== null ) {
  47304. srcX = srcRegion.x;
  47305. srcY = srcRegion.y;
  47306. srcLayer = srcRegion.z || 0;
  47307. srcWidth = srcRegion.width;
  47308. srcHeight = srcRegion.height;
  47309. }
  47310. if ( dstPosition !== null ) {
  47311. dstX = dstPosition.x;
  47312. dstY = dstPosition.y;
  47313. dstLayer = dstPosition.z || 0;
  47314. }
  47315. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  47316. const sourceGPU = this.get( srcTexture ).texture;
  47317. const destinationGPU = this.get( dstTexture ).texture;
  47318. encoder.copyTextureToTexture(
  47319. {
  47320. texture: sourceGPU,
  47321. mipLevel: level,
  47322. origin: { x: srcX, y: srcY, z: srcLayer }
  47323. },
  47324. {
  47325. texture: destinationGPU,
  47326. mipLevel: level,
  47327. origin: { x: dstX, y: dstY, z: dstLayer }
  47328. },
  47329. [
  47330. srcWidth,
  47331. srcHeight,
  47332. 1
  47333. ]
  47334. );
  47335. this.device.queue.submit( [ encoder.finish() ] );
  47336. }
  47337. /**
  47338. * Copies the current bound framebuffer to the given texture.
  47339. *
  47340. * @param {Texture} texture - The destination texture.
  47341. * @param {RenderContext} renderContext - The render context.
  47342. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47343. */
  47344. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47345. const renderContextData = this.get( renderContext );
  47346. let sourceGPU = null;
  47347. if ( renderContext.renderTarget ) {
  47348. if ( texture.isDepthTexture ) {
  47349. sourceGPU = this.get( renderContext.depthTexture ).texture;
  47350. } else {
  47351. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  47352. }
  47353. } else {
  47354. if ( texture.isDepthTexture ) {
  47355. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  47356. } else {
  47357. sourceGPU = this.context.getCurrentTexture();
  47358. }
  47359. }
  47360. const destinationGPU = this.get( texture ).texture;
  47361. if ( sourceGPU.format !== destinationGPU.format ) {
  47362. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  47363. return;
  47364. }
  47365. let encoder;
  47366. if ( renderContextData.currentPass ) {
  47367. renderContextData.currentPass.end();
  47368. encoder = renderContextData.encoder;
  47369. } else {
  47370. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  47371. }
  47372. encoder.copyTextureToTexture(
  47373. {
  47374. texture: sourceGPU,
  47375. origin: [ rectangle.x, rectangle.y, 0 ],
  47376. },
  47377. {
  47378. texture: destinationGPU
  47379. },
  47380. [
  47381. rectangle.z,
  47382. rectangle.w
  47383. ]
  47384. );
  47385. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  47386. if ( renderContextData.currentPass ) {
  47387. const { descriptor } = renderContextData;
  47388. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  47389. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  47390. }
  47391. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47392. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47393. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  47394. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47395. if ( renderContext.viewport ) {
  47396. this.updateViewport( renderContext );
  47397. }
  47398. if ( renderContext.scissor ) {
  47399. const { x, y, width, height } = renderContext.scissorValue;
  47400. renderContextData.currentPass.setScissorRect( x, y, width, height );
  47401. }
  47402. } else {
  47403. this.device.queue.submit( [ encoder.finish() ] );
  47404. }
  47405. }
  47406. }
  47407. class IESSpotLight extends SpotLight {
  47408. constructor( color, intensity, distance, angle, penumbra, decay ) {
  47409. super( color, intensity, distance, angle, penumbra, decay );
  47410. this.iesMap = null;
  47411. }
  47412. copy( source, recursive ) {
  47413. super.copy( source, recursive );
  47414. this.iesMap = source.iesMap;
  47415. return this;
  47416. }
  47417. }
  47418. /**
  47419. * This version of a node library represents the standard version
  47420. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  47421. * techniques and materials to node-based implementations.
  47422. *
  47423. * @private
  47424. * @augments NodeLibrary
  47425. */
  47426. class StandardNodeLibrary extends NodeLibrary {
  47427. /**
  47428. * Constructs a new standard node library.
  47429. */
  47430. constructor() {
  47431. super();
  47432. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  47433. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  47434. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  47435. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  47436. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  47437. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  47438. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  47439. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  47440. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  47441. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  47442. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  47443. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  47444. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  47445. this.addLight( PointLightNode, PointLight );
  47446. this.addLight( DirectionalLightNode, DirectionalLight );
  47447. this.addLight( RectAreaLightNode, RectAreaLight );
  47448. this.addLight( SpotLightNode, SpotLight );
  47449. this.addLight( AmbientLightNode, AmbientLight );
  47450. this.addLight( HemisphereLightNode, HemisphereLight );
  47451. this.addLight( LightProbeNode, LightProbe );
  47452. this.addLight( IESSpotLightNode, IESSpotLight );
  47453. this.addToneMapping( linearToneMapping, LinearToneMapping );
  47454. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  47455. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  47456. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  47457. this.addToneMapping( agxToneMapping, AgXToneMapping );
  47458. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  47459. }
  47460. }
  47461. /*
  47462. const debugHandler = {
  47463. get: function ( target, name ) {
  47464. // Add |update
  47465. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  47466. return target[ name ];
  47467. }
  47468. };
  47469. */
  47470. /**
  47471. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  47472. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  47473. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  47474. *
  47475. * @augments module:Renderer~Renderer
  47476. */
  47477. class WebGPURenderer extends Renderer {
  47478. /**
  47479. * Constructs a new WebGPU renderer.
  47480. *
  47481. * @param {Object} parameters - The configuration parameter.
  47482. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47483. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47484. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47485. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47486. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47487. * @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.
  47488. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47489. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  47490. */
  47491. constructor( parameters = {} ) {
  47492. let BackendClass;
  47493. if ( parameters.forceWebGL ) {
  47494. BackendClass = WebGLBackend;
  47495. } else {
  47496. BackendClass = WebGPUBackend;
  47497. parameters.getFallback = () => {
  47498. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  47499. return new WebGLBackend( parameters );
  47500. };
  47501. }
  47502. const backend = new BackendClass( parameters );
  47503. //super( new Proxy( backend, debugHandler ) );
  47504. super( backend, parameters );
  47505. /**
  47506. * The generic default value is overwritten with the
  47507. * standard node library for type mapping.
  47508. *
  47509. * @type {StandardNodeLibrary}
  47510. */
  47511. this.library = new StandardNodeLibrary();
  47512. /**
  47513. * This flag can be used for type testing.
  47514. *
  47515. * @type {Boolean}
  47516. * @readonly
  47517. * @default true
  47518. */
  47519. this.isWebGPURenderer = true;
  47520. }
  47521. }
  47522. /**
  47523. * A specialized group which enables applications access to the
  47524. * Render Bundle API of WebGPU. The group with all its descendant nodes
  47525. * are considered as one render bundle and processed as such by
  47526. * the renderer.
  47527. *
  47528. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  47529. * With a WebGL backend, the group can technically be rendered but without
  47530. * any performance improvements.
  47531. *
  47532. * @augments Group
  47533. */
  47534. class BundleGroup extends Group {
  47535. /**
  47536. * Constructs a new bundle group.
  47537. */
  47538. constructor() {
  47539. super();
  47540. /**
  47541. * This flag can be used for type testing.
  47542. *
  47543. * @type {Boolean}
  47544. * @readonly
  47545. * @default true
  47546. */
  47547. this.isBundleGroup = true;
  47548. /**
  47549. * This property is only relevant for detecting types
  47550. * during serialization/deserialization. It should always
  47551. * match the class name.
  47552. *
  47553. * @type {String}
  47554. * @readonly
  47555. * @default 'BundleGroup'
  47556. */
  47557. this.type = 'BundleGroup';
  47558. /**
  47559. * Whether the bundle is static or not. When set to `true`, the structure
  47560. * is assumed to be static and does not change. E.g. no new objects are
  47561. * added to the group
  47562. *
  47563. * If a change is required, an update can still be forced by setting the
  47564. * `needsUpdate` flag to `true`.
  47565. *
  47566. * @type {Boolean}
  47567. * @default true
  47568. */
  47569. this.static = true;
  47570. /**
  47571. * The bundle group's version.
  47572. *
  47573. * @type {Number}
  47574. * @readonly
  47575. * @default 0
  47576. */
  47577. this.version = 0;
  47578. }
  47579. /**
  47580. * Set this property to `true` when the bundle group has changed.
  47581. *
  47582. * @type {Boolean}
  47583. * @default false
  47584. * @param {Boolean} value
  47585. */
  47586. set needsUpdate( value ) {
  47587. if ( value === true ) this.version ++;
  47588. }
  47589. }
  47590. /**
  47591. * This module is responsible to manage the post processing setups in apps.
  47592. * You usually create a single instance of this class and use it to define
  47593. * the output of your post processing effect chain.
  47594. * ```js
  47595. * const postProcessing = new PostProcessing( renderer );
  47596. *
  47597. * const scenePass = pass( scene, camera );
  47598. *
  47599. * postProcessing.outputNode = scenePass;
  47600. * ```
  47601. */
  47602. class PostProcessing {
  47603. /**
  47604. * Constructs a new post processing management module.
  47605. *
  47606. * @param {Renderer} renderer - A reference to the renderer.
  47607. * @param {Node<vec4>} outputNode - An optional output node.
  47608. */
  47609. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  47610. /**
  47611. * A reference to the renderer.
  47612. *
  47613. * @type {Renderer}
  47614. */
  47615. this.renderer = renderer;
  47616. /**
  47617. * A node which defines the final output of the post
  47618. * processing. This is usually the last node in a chain
  47619. * of effect nodes.
  47620. *
  47621. * @type {Node<vec4>}
  47622. */
  47623. this.outputNode = outputNode;
  47624. /**
  47625. * Whether the default output tone mapping and color
  47626. * space transformation should be enabled or not.
  47627. *
  47628. * It is enabled by default by it must be disabled when
  47629. * effects must be executed after tone mapping and color
  47630. * space conversion. A typical example is FXAA which
  47631. * requires sRGB input.
  47632. *
  47633. * When set to `false`, the app must control the output
  47634. * transformation with `RenderOutputNode`.
  47635. *
  47636. * ```js
  47637. * const outputPass = renderOutput( scenePass );
  47638. * ```
  47639. *
  47640. * @type {Boolean}
  47641. */
  47642. this.outputColorTransform = true;
  47643. /**
  47644. * Must be set to `true` when the output node changes.
  47645. *
  47646. * @type {Node<vec4>}
  47647. */
  47648. this.needsUpdate = true;
  47649. const material = new NodeMaterial();
  47650. material.name = 'PostProcessing';
  47651. /**
  47652. * The full screen quad that is used to render
  47653. * the effects.
  47654. *
  47655. * @private
  47656. * @type {QuadMesh}
  47657. */
  47658. this._quadMesh = new QuadMesh( material );
  47659. }
  47660. /**
  47661. * When `PostProcessing` is used to apply post processing effects,
  47662. * the application must use this version of `render()` inside
  47663. * its animation loop (not the one from the renderer).
  47664. */
  47665. render() {
  47666. this._update();
  47667. const renderer = this.renderer;
  47668. const toneMapping = renderer.toneMapping;
  47669. const outputColorSpace = renderer.outputColorSpace;
  47670. renderer.toneMapping = NoToneMapping;
  47671. renderer.outputColorSpace = LinearSRGBColorSpace;
  47672. //
  47673. this._quadMesh.render( renderer );
  47674. //
  47675. renderer.toneMapping = toneMapping;
  47676. renderer.outputColorSpace = outputColorSpace;
  47677. }
  47678. /**
  47679. * Frees internal resources.
  47680. */
  47681. dispose() {
  47682. this._quadMesh.material.dispose();
  47683. }
  47684. /**
  47685. * Updates the state of the module.
  47686. *
  47687. * @private
  47688. */
  47689. _update() {
  47690. if ( this.needsUpdate === true ) {
  47691. const renderer = this.renderer;
  47692. const toneMapping = renderer.toneMapping;
  47693. const outputColorSpace = renderer.outputColorSpace;
  47694. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  47695. this._quadMesh.material.needsUpdate = true;
  47696. this.needsUpdate = false;
  47697. }
  47698. }
  47699. /**
  47700. * When `PostProcessing` is used to apply post processing effects,
  47701. * the application must use this version of `renderAsync()` inside
  47702. * its animation loop (not the one from the renderer).
  47703. *
  47704. * @async
  47705. * @return {Promise} A Promise that resolves when the render has been finished.
  47706. */
  47707. async renderAsync() {
  47708. this._update();
  47709. const renderer = this.renderer;
  47710. const toneMapping = renderer.toneMapping;
  47711. const outputColorSpace = renderer.outputColorSpace;
  47712. renderer.toneMapping = NoToneMapping;
  47713. renderer.outputColorSpace = LinearSRGBColorSpace;
  47714. //
  47715. await this._quadMesh.renderAsync( renderer );
  47716. //
  47717. renderer.toneMapping = toneMapping;
  47718. renderer.outputColorSpace = outputColorSpace;
  47719. }
  47720. }
  47721. /**
  47722. * This special type of texture is intended for compute shaders.
  47723. * It can be used to compute the data of a texture with a compute shader.
  47724. *
  47725. * Note: This type of texture can only be used with `WebGPURenderer`
  47726. * and a WebGPU backend.
  47727. *
  47728. * @augments Texture
  47729. */
  47730. class StorageTexture extends Texture {
  47731. /**
  47732. * Constructs a new storage texture.
  47733. *
  47734. * @param {Number} [width=1] - The storage texture's width.
  47735. * @param {Number} [height=1] - The storage texture's height.
  47736. */
  47737. constructor( width = 1, height = 1 ) {
  47738. super();
  47739. /**
  47740. * The image object which just represents the texture's dimension.
  47741. *
  47742. * @type {{width: Number, height: Number}}
  47743. */
  47744. this.image = { width, height };
  47745. /**
  47746. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  47747. *
  47748. * @type {Number}
  47749. */
  47750. this.magFilter = LinearFilter;
  47751. /**
  47752. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  47753. *
  47754. * @type {Number}
  47755. */
  47756. this.minFilter = LinearFilter;
  47757. /**
  47758. * This flag can be used for type testing.
  47759. *
  47760. * @type {Boolean}
  47761. * @readonly
  47762. * @default true
  47763. */
  47764. this.isStorageTexture = true;
  47765. }
  47766. }
  47767. /**
  47768. * This special type of buffer attribute is intended for compute shaders.
  47769. * It can be used to encode draw parameters for indirect draw calls.
  47770. *
  47771. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  47772. * and a WebGPU backend.
  47773. *
  47774. * @augments StorageBufferAttribute
  47775. */
  47776. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  47777. /**
  47778. * Constructs a new storage buffer attribute.
  47779. *
  47780. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  47781. * The subsequent parameter is then obsolete.
  47782. * @param {Number} itemSize - The item size.
  47783. */
  47784. constructor( count, itemSize ) {
  47785. super( count, itemSize, Uint32Array );
  47786. /**
  47787. * This flag can be used for type testing.
  47788. *
  47789. * @type {Boolean}
  47790. * @readonly
  47791. * @default true
  47792. */
  47793. this.isIndirectStorageBufferAttribute = true;
  47794. }
  47795. }
  47796. /**
  47797. * A loader for loading node objects in the three.js JSON Object/Scene format.
  47798. *
  47799. * @augments Loader
  47800. */
  47801. class NodeLoader extends Loader {
  47802. /**
  47803. * Constructs a new node loader.
  47804. *
  47805. * @param {LoadingManager?} manager - A reference to a loading manager.
  47806. */
  47807. constructor( manager ) {
  47808. super( manager );
  47809. /**
  47810. * Represents a dictionary of textures.
  47811. *
  47812. * @type {Object<String,Texture>}
  47813. */
  47814. this.textures = {};
  47815. /**
  47816. * Represents a dictionary of node types.
  47817. *
  47818. * @type {Object<String,Node.constructor>}
  47819. */
  47820. this.nodes = {};
  47821. }
  47822. /**
  47823. * Loads the node definitions from the given URL.
  47824. *
  47825. * @param {String} url - The path/URL of the file to be loaded.
  47826. * @param {Function} onLoad - Will be called when load completes.
  47827. * @param {Function} onProgress - Will be called while load progresses.
  47828. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  47829. */
  47830. load( url, onLoad, onProgress, onError ) {
  47831. const loader = new FileLoader( this.manager );
  47832. loader.setPath( this.path );
  47833. loader.setRequestHeader( this.requestHeader );
  47834. loader.setWithCredentials( this.withCredentials );
  47835. loader.load( url, ( text ) => {
  47836. try {
  47837. onLoad( this.parse( JSON.parse( text ) ) );
  47838. } catch ( e ) {
  47839. if ( onError ) {
  47840. onError( e );
  47841. } else {
  47842. console.error( e );
  47843. }
  47844. this.manager.itemError( url );
  47845. }
  47846. }, onProgress, onError );
  47847. }
  47848. /**
  47849. * Parse the node dependencies for the loaded node.
  47850. *
  47851. * @param {Object} json - The JSON definition
  47852. * @return {Object<String,Node>} A dictionary with node dependencies.
  47853. */
  47854. parseNodes( json ) {
  47855. const nodes = {};
  47856. if ( json !== undefined ) {
  47857. for ( const nodeJSON of json ) {
  47858. const { uuid, type } = nodeJSON;
  47859. nodes[ uuid ] = this.createNodeFromType( type );
  47860. nodes[ uuid ].uuid = uuid;
  47861. }
  47862. const meta = { nodes, textures: this.textures };
  47863. for ( const nodeJSON of json ) {
  47864. nodeJSON.meta = meta;
  47865. const node = nodes[ nodeJSON.uuid ];
  47866. node.deserialize( nodeJSON );
  47867. delete nodeJSON.meta;
  47868. }
  47869. }
  47870. return nodes;
  47871. }
  47872. /**
  47873. * Parses the node from the given JSON.
  47874. *
  47875. * @param {Object} json - The JSON definition
  47876. * @return {Node} The parsed node.
  47877. */
  47878. parse( json ) {
  47879. const node = this.createNodeFromType( json.type );
  47880. node.uuid = json.uuid;
  47881. const nodes = this.parseNodes( json.nodes );
  47882. const meta = { nodes, textures: this.textures };
  47883. json.meta = meta;
  47884. node.deserialize( json );
  47885. delete json.meta;
  47886. return node;
  47887. }
  47888. /**
  47889. * Defines the dictionary of textures.
  47890. *
  47891. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  47892. * @return {NodeLoader} A reference to this loader.
  47893. */
  47894. setTextures( value ) {
  47895. this.textures = value;
  47896. return this;
  47897. }
  47898. /**
  47899. * Defines the dictionary of node types.
  47900. *
  47901. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  47902. * @return {NodeLoader} A reference to this loader.
  47903. */
  47904. setNodes( value ) {
  47905. this.nodes = value;
  47906. return this;
  47907. }
  47908. /**
  47909. * Creates a node object from the given type.
  47910. *
  47911. * @param {String} type - The node type.
  47912. * @return {Node} The created node instance.
  47913. */
  47914. createNodeFromType( type ) {
  47915. if ( this.nodes[ type ] === undefined ) {
  47916. console.error( 'THREE.NodeLoader: Node type not found:', type );
  47917. return float();
  47918. }
  47919. return nodeObject( new this.nodes[ type ]() );
  47920. }
  47921. }
  47922. /**
  47923. * A special type of material loader for loading node materials.
  47924. *
  47925. * @augments MaterialLoader
  47926. */
  47927. class NodeMaterialLoader extends MaterialLoader {
  47928. /**
  47929. * Constructs a new node material loader.
  47930. *
  47931. * @param {LoadingManager?} manager - A reference to a loading manager.
  47932. */
  47933. constructor( manager ) {
  47934. super( manager );
  47935. /**
  47936. * Represents a dictionary of node types.
  47937. *
  47938. * @type {Object<String,Node.constructor>}
  47939. */
  47940. this.nodes = {};
  47941. /**
  47942. * Represents a dictionary of node material types.
  47943. *
  47944. * @type {Object<String,NodeMaterial.constructor>}
  47945. */
  47946. this.nodeMaterials = {};
  47947. }
  47948. /**
  47949. * Parses the node material from the given JSON.
  47950. *
  47951. * @param {Object} json - The JSON definition
  47952. * @return {NodeMaterial}. The parsed material.
  47953. */
  47954. parse( json ) {
  47955. const material = super.parse( json );
  47956. const nodes = this.nodes;
  47957. const inputNodes = json.inputNodes;
  47958. for ( const property in inputNodes ) {
  47959. const uuid = inputNodes[ property ];
  47960. material[ property ] = nodes[ uuid ];
  47961. }
  47962. return material;
  47963. }
  47964. /**
  47965. * Defines the dictionary of node types.
  47966. *
  47967. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  47968. * @return {NodeLoader} A reference to this loader.
  47969. */
  47970. setNodes( value ) {
  47971. this.nodes = value;
  47972. return this;
  47973. }
  47974. /**
  47975. * Defines the dictionary of node material types.
  47976. *
  47977. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  47978. * @return {NodeLoader} A reference to this loader.
  47979. */
  47980. setNodeMaterials( value ) {
  47981. this.nodeMaterials = value;
  47982. return this;
  47983. }
  47984. /**
  47985. * Creates a node material from the given type.
  47986. *
  47987. * @param {String} type - The node material type.
  47988. * @return {Node} The created node material instance.
  47989. */
  47990. createMaterialFromType( type ) {
  47991. const materialClass = this.nodeMaterials[ type ];
  47992. if ( materialClass !== undefined ) {
  47993. return new materialClass();
  47994. }
  47995. return super.createMaterialFromType( type );
  47996. }
  47997. }
  47998. /**
  47999. * A special type of object loader for loading 3D objects using
  48000. * node materials.
  48001. *
  48002. * @augments ObjectLoader
  48003. */
  48004. class NodeObjectLoader extends ObjectLoader {
  48005. /**
  48006. * Constructs a new node object loader.
  48007. *
  48008. * @param {LoadingManager?} manager - A reference to a loading manager.
  48009. */
  48010. constructor( manager ) {
  48011. super( manager );
  48012. /**
  48013. * Represents a dictionary of node types.
  48014. *
  48015. * @type {Object<String,Node.constructor>}
  48016. */
  48017. this.nodes = {};
  48018. /**
  48019. * Represents a dictionary of node material types.
  48020. *
  48021. * @type {Object<String,NodeMaterial.constructor>}
  48022. */
  48023. this.nodeMaterials = {};
  48024. /**
  48025. * A reference to hold the `nodes` JSON property.
  48026. *
  48027. * @private
  48028. * @type {Object?}
  48029. */
  48030. this._nodesJSON = null;
  48031. }
  48032. /**
  48033. * Defines the dictionary of node types.
  48034. *
  48035. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48036. * @return {NodeLoader} A reference to this loader.
  48037. */
  48038. setNodes( value ) {
  48039. this.nodes = value;
  48040. return this;
  48041. }
  48042. /**
  48043. * Defines the dictionary of node material types.
  48044. *
  48045. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48046. * @return {NodeLoader} A reference to this loader.
  48047. */
  48048. setNodeMaterials( value ) {
  48049. this.nodeMaterials = value;
  48050. return this;
  48051. }
  48052. /**
  48053. * Parses the node objects from the given JSON.
  48054. *
  48055. * @param {Object} json - The JSON definition
  48056. * @param {Function} onLoad - The onLoad callback function.
  48057. * @return {Object3D}. The parsed 3D object.
  48058. */
  48059. parse( json, onLoad ) {
  48060. this._nodesJSON = json.nodes;
  48061. const data = super.parse( json, onLoad );
  48062. this._nodesJSON = null; // dispose
  48063. return data;
  48064. }
  48065. /**
  48066. * Parses the node objects from the given JSON and textures.
  48067. *
  48068. * @param {Object} json - The JSON definition
  48069. * @param {Object<String,Texture>} textures - The texture library.
  48070. * @return {Object<String,Node>}. The parsed nodes.
  48071. */
  48072. parseNodes( json, textures ) {
  48073. if ( json !== undefined ) {
  48074. const loader = new NodeLoader();
  48075. loader.setNodes( this.nodes );
  48076. loader.setTextures( textures );
  48077. return loader.parseNodes( json );
  48078. }
  48079. return {};
  48080. }
  48081. /**
  48082. * Parses the node objects from the given JSON and textures.
  48083. *
  48084. * @param {Object} json - The JSON definition
  48085. * @param {Object<String,Texture>} textures - The texture library.
  48086. * @return {Object<String,NodeMaterial>}. The parsed materials.
  48087. */
  48088. parseMaterials( json, textures ) {
  48089. const materials = {};
  48090. if ( json !== undefined ) {
  48091. const nodes = this.parseNodes( this._nodesJSON, textures );
  48092. const loader = new NodeMaterialLoader();
  48093. loader.setTextures( textures );
  48094. loader.setNodes( nodes );
  48095. loader.setNodeMaterials( this.nodeMaterials );
  48096. for ( let i = 0, l = json.length; i < l; i ++ ) {
  48097. const data = json[ i ];
  48098. materials[ data.uuid ] = loader.parse( data );
  48099. }
  48100. }
  48101. return materials;
  48102. }
  48103. }
  48104. /**
  48105. * In earlier three.js versions, clipping was defined globally
  48106. * on the renderer or on material level. This special version of
  48107. * `THREE.Group` allows to encode the clipping state into the scene
  48108. * graph. Meaning if you create an instance of this group, all
  48109. * descendant 3D objects will be affected by the respective clipping
  48110. * planes.
  48111. *
  48112. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  48113. *
  48114. * @augments Group
  48115. */
  48116. class ClippingGroup extends Group {
  48117. /**
  48118. * Constructs a new clipping group.
  48119. */
  48120. constructor() {
  48121. super();
  48122. /**
  48123. * This flag can be used for type testing.
  48124. *
  48125. * @type {Boolean}
  48126. * @readonly
  48127. * @default true
  48128. */
  48129. this.isClippingGroup = true;
  48130. /**
  48131. * An array with clipping planes.
  48132. *
  48133. * @type {Array<Plane>}
  48134. */
  48135. this.clippingPlanes = [];
  48136. /**
  48137. * Whether clipping should be enabled or not.
  48138. *
  48139. * @type {Boolean}
  48140. * @default true
  48141. */
  48142. this.enabled = true;
  48143. /**
  48144. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  48145. *
  48146. * @type {Boolean}
  48147. * @default false
  48148. */
  48149. this.clipIntersection = false;
  48150. /**
  48151. * Whether shadows should be clipped or not.
  48152. *
  48153. * @type {Boolean}
  48154. * @default false
  48155. */
  48156. this.clipShadows = false;
  48157. }
  48158. }
  48159. 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号